更新 :  2018-01-22 

之前漏掉了一个 image 优化, 就是 progressive jpg

refer :

http://techslides.com/demos/progressive-test.html (online test)

http://magick.codeplex.com/discussions/450804 (Magick)

https://www.imgonline.com.ua/eng/make-jpeg-progressive-without-compression-result.php (online convert)

https://developers.google.com/speed/docs/insights/OptimizeImages (google 优化图片指南)

image.Settings.SetDefine(MagickFormat.Jpeg, "sampling-factor", "4:2:0");
image.Format = MagickFormat.Pjpeg; // 转换成 progressive jpg
image.Strip(); //这句会把图片的所有 EXIF 洗掉
image.Quality = ;

2017-09-25

refer : https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads

https://www.codeproject.com/Articles/1203408/Upload-Download-Files-in-ASP-NET-Core

这里只说说小文件上传.

先看看前端 js 代码

<input id="inputFile" type="file" />
<script>
document.getElementById('inputFile').addEventListener('change', (e) => {
let files = e.target.files;
let formData = new FormData();
formData.append("file", files[0]);
let http = new XMLHttpRequest();
http.open('POST', '/upload-file', true);
http.send(formData);
}, false);
</script>

如果要上传多个文件就 append 多几个就是了

c#

public class UploadFileData
{
public IFormFile file { get; set; }
} [Area("Web")]
public class UploadController : Controller
{
public UploadController(
IHostingEnvironment environment
)
{
this.environment = environment;
} private IHostingEnvironment environment { get; set; } [HttpPost("upload-file")]
public async Task<IActionResult> uploadFile(UploadFileData data)
{
var allFiles = Request.Form.Files; // 多文件的话可以直接从 form 拿到完, 或则设置成 List<IFormFile> 就可以了
var root = environment.WebRootPath;
var extension = Path.GetExtension(data.file.FileName);
var guid = Guid.NewGuid().ToString();
var fullPath = $@"{root}\images\{guid + extension}";
using (FileStream stream = new FileStream(fullPath, FileMode.Create))
{
await data.file.CopyToAsync(stream);
}
return Ok();
}
[Route("upload")]
public async Task<IActionResult> Index()
{
return View();
}
}

上面的是最简单的版本,创建 file 然后把 upload file stream 写入

如果是想直接使用 stream 也是可以

using (var memoryStream = new MemoryStream())
{
await model.file.CopyToAsync(memoryStream);
memoryStream.Seek(, SeekOrigin.Begin);
new FileExtensionContentTypeProvider().TryGetContentType(model.file.FileName, out string contentType); await EmailService.SendAsync(
recipients: BusinessConfig.contactEmailHandler,
subject: "Contact form from website",
templatePath: "~/Email/Contact/Index.cshtml",
model: model,
attachs: new List<Attachment> { new Attachment(memoryStream, model.file.FileName, contentType ?? "application/octet-stream") }
);
}

需要注意的是写入 stream 后, 如果要读取 stream 记得, Seek 一下.

还有一个常用的场景是, 上传图片要做 EXIF 处理.

可以用 Magick.NET 目前支持 core, 不过呢, 好像只支持 window 场景. 如果你不是 windows 可能要在等等或则用其它插件.

Magick 需要设置, 参考 : https://magick.codeplex.com/documentation

MagickAnyCPU.CacheDirectory = @"C:\MyProgram\MyTempDir";
MagickNET.SetTempDirectory(@"C:\MyProgram\MyTempFiles");
例子
using (var stream = data.file.OpenReadStream())
using (MagickImage image = new MagickImage(stream))
{
ExifProfile profile = image.GetExifProfile();
image.Settings.SetDefine(MagickFormat.Jpeg, "sampling-factor", "4:2:0");
image.Strip(); //这句会把图片的所有 EXIF 洗掉
image.Quality = ; if (profile != null)
{
ExifValue orientation = profile.Values.SingleOrDefault(v => v.Tag == ExifTag.Orientation);
if (orientation != null)
{
int orientationInt = Convert.ToInt32(orientation.Value);
if (orientationInt == )
{
image.Rotate();
}
else if (orientationInt == )
{
image.Rotate(-);
}
else if (orientationInt == )
{
image.Rotate();
}
}
image.Write(fullPath);
}
else
{
image.Write(fullPath);
}
}

很简单吧.

再来一个 zip 的

using (var stream = data.file.OpenReadStream())
using (var compressedFileStream = new FileStream($@"{root}\images\{guid}.zip", FileMode.Create))
using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false))
{
var zipEntry = zipArchive.CreateEntry(data.file.FileName);
using (var zipEntryStream = zipEntry.Open())
{
stream.CopyTo(zipEntryStream);
}
}

core 支持 ZipArchive 哦

下载也很容易

public UploadController(
IHostingEnvironment environment,
IContentTypeProvider contentTypeProvider
)
{
this.environment = environment;
this.contentTypeProvider = contentTypeProvider;
} private IHostingEnvironment environment { get; set; }
private IContentTypeProvider contentTypeProvider { get; set; } [HttpGet("download-file")]
public FileResult downloadFile(string name, string display)
{
string contentType;
contentTypeProvider.TryGetContentType(name, out contentType);
HttpContext.Response.ContentType = contentType;
string path = environment.WebRootPath + @"\images\" + name; // 注意哦, 不要像我这样直接使用客户端的值来拼接 path, 危险的
FileContentResult result = new FileContentResult(System.IO.File.ReadAllBytes(path), contentType)
{
FileDownloadName = display
};
   // return File("~/excels/report.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "report.xlsx"); // 返回 File + 路径也是可以, 这个路径是从 wwwroot 走起
   // return File(await System.IO.File.ReadAllBytesAsync(path), same...) // 或则我们可以直接返回 byte[], 任意从哪里获取都可以.
return result;
}

html

<a href="/download-file?name=123.jpg&display=aaa.jpg" download  >download</a>

Asp.net core 学习笔记 ( upload/download files 文件上传与下载 )的更多相关文章

  1. 2014-07-23 利用ASP.NET自带控件实现单文件上传与下载

    效果图 上传文件页面: 下载文件页面:  1.母版页site.Master <%@ Master Language="C#" AutoEventWireup="tr ...

  2. Java Web 学习(8) —— Spring MVC 之文件上传与下载

    Spring MVC 之文件上传与下载 上传文件 表单: <form action="upload" enctype="multipart/form-data&qu ...

  3. 《Play for Java》学习笔记(六)文件上传file upload

    一. Play中标准方法 使用表单form和multipart/form-data的content-type类型. 1.Form @form(action = routes.Application.u ...

  4. Nodejs学习笔记(5) 文件上传系统实例

    目录 2018.8.4更新:  MySQL可以存放几乎任何类型的数据(图片.文档.压缩包等),但这不是最好的解决方案,正常情况下都是在数据库中存放文件路径,图片.音乐.视频.压缩包.文档等文件存放在硬 ...

  5. Django学习笔记之Ajax与文件上传

      Ajax简介 AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步Javascript和XML”.即使用Javascript语言与服务器进行异步交互,传输 ...

  6. 老男孩 python学习自修第二十二天【文件上传与下载】

    1.使用socket实现文件上传 server.py #!/usr/bin/env python # _*_ coding:UTF-8 _*_ import os import SocketServe ...

  7. JMeter学习笔记(五) 文件上传接口测试

    此次测试的是上传图片接口,我把测试情况整理了一下,其他的上传文件接口都类似. 1.我通过jmeter的录制功能获取到了接口地址以及相关参数,如果有接口文档就会方便很多,此步骤就不多做说明了 2.因为上 ...

  8. java web 学习笔记 - jsp用的文件上传组件 SmartUpload

    ---恢复内容开始--- 1. SmartUpload 此控件在jsp中被广泛的使用,而FileUpload控件主要是用在框架中 2. 如果想要使用,需要在tomcat的lib目录中,将SmartUp ...

  9. PHP学习笔记(9)文件上传

    index.php <!doctype html> <html lang="en"> <head> <meta charset=" ...

随机推荐

  1. sql xml 入门 (二)

    DECLARE @myDoc xml --http://www.paymob.cn --话费充值api,充值api,话费充值接口,手机话费充值,车贝手机,贝萌手机,移动话费充值,联通话费充值,电信话费 ...

  2. 火车时刻表WebApp

    关键词 :Ajax 跨域访问 php 同源策略 JQueryMobile 前言 在面试的过程中,兄弟连的徐老师提出要求我用JQuery Mobile(前端框架)来实现一个具有“火车时刻表”功能的Web ...

  3. bzoj 4540 [HNOI 2016] 序列 - 莫队算法 - Sparse-Table - 单调栈

    题目传送门 传送点I 传送点II 题目大意 给定一个长度为$n$的序列.询问区间$[l, r]$的所有不同的子序列的最小值的和. 这里的子序列是连续的.两个子序列不同当且仅当它们的左端点或右端点不同. ...

  4. Xcode project 设置相关

    FauxPas 这是一款Mac平台的用于检查Xcode项目的辅助工具 ,可以帮助我们找出常见的错误.隐藏的bug.不良实践以及可维护性问题和风格问题. 一, $(SRCROOT)  :当前工程所在的目 ...

  5. FBX SDK在vs 2010下面的配置

    1.下载FBS SDK.地址.因为我是vs2010,所以我下载的是FBX SDK 2016.1.2 VS2010.如果没有了,你可以找博主直接要,QQ1240957820. 2.下载下来的是一个exe ...

  6. Spring 学习——Spring常用注解——@Component、@Scope、@Repository、@Service、@Controller、@Required、@Autowired、@Qualifier、@Configuration、@ImportResource、@Value

    Bean管理注解实现 Classpath扫描与组件管理 类的自动检测与注册Bean 类的注解@Component.@Service等作用是将这个实例自动装配到Bean容器中管理 而类似于@Autowi ...

  7. 【做题】CF239E. k-d-sequence——线段树

    首先,容易得到判断一个子串为"good k-d sequence"的方法: 子串中没有重复元素,且所有元素模d相等. 记mx为除以d的最大值,mn为除以d的最小值,则\(mx-mn ...

  8. 【入门】Gradle的基本使用、在IDEA中的配置、常用命令

    一.介绍 java的源码构建工具,大致经历了 ant -> maven -> gradle 这个过程,每一次进步,都是在解决之前的工具所带来的问题,简单来说: 1. ant 功能虽然也很强 ...

  9. DataTabel 与DataView之间的转化

    DataTable转为DataView,或者反之转化, 使用的是文档/试图模型,DataTable可以有多个视图,这样就可以不需要借助List类型对dataTable数据进行筛选或者排序 //Data ...

  10. SQL语句执行的顺序机制

    From Where Group by Having Select 表达式 Distinct ORDER BY TOP/OFFSET-FETCH