Asp.net core 学习笔记 ( upload/download files 文件上传与下载 )
更新 : 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 文件上传与下载 )的更多相关文章
- 2014-07-23 利用ASP.NET自带控件实现单文件上传与下载
效果图 上传文件页面: 下载文件页面: 1.母版页site.Master <%@ Master Language="C#" AutoEventWireup="tr ...
- Java Web 学习(8) —— Spring MVC 之文件上传与下载
Spring MVC 之文件上传与下载 上传文件 表单: <form action="upload" enctype="multipart/form-data&qu ...
- 《Play for Java》学习笔记(六)文件上传file upload
一. Play中标准方法 使用表单form和multipart/form-data的content-type类型. 1.Form @form(action = routes.Application.u ...
- Nodejs学习笔记(5) 文件上传系统实例
目录 2018.8.4更新: MySQL可以存放几乎任何类型的数据(图片.文档.压缩包等),但这不是最好的解决方案,正常情况下都是在数据库中存放文件路径,图片.音乐.视频.压缩包.文档等文件存放在硬 ...
- Django学习笔记之Ajax与文件上传
Ajax简介 AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步Javascript和XML”.即使用Javascript语言与服务器进行异步交互,传输 ...
- 老男孩 python学习自修第二十二天【文件上传与下载】
1.使用socket实现文件上传 server.py #!/usr/bin/env python # _*_ coding:UTF-8 _*_ import os import SocketServe ...
- JMeter学习笔记(五) 文件上传接口测试
此次测试的是上传图片接口,我把测试情况整理了一下,其他的上传文件接口都类似. 1.我通过jmeter的录制功能获取到了接口地址以及相关参数,如果有接口文档就会方便很多,此步骤就不多做说明了 2.因为上 ...
- java web 学习笔记 - jsp用的文件上传组件 SmartUpload
---恢复内容开始--- 1. SmartUpload 此控件在jsp中被广泛的使用,而FileUpload控件主要是用在框架中 2. 如果想要使用,需要在tomcat的lib目录中,将SmartUp ...
- PHP学习笔记(9)文件上传
index.php <!doctype html> <html lang="en"> <head> <meta charset=" ...
随机推荐
- 03: pip使用
1.1 pip常用方法 1.自我升级(升级pip到最新版本) pip install --upgrade pip 2. 安装库 pip install XXX 3. 查看当前环境所有已安装的库 pip ...
- 搭建ldap服务器及web管理服务--phpldapadmin
系统版本:centos6 安装配置openldap: yum install openldap openldap-servers openldap-clients openldap-devel com ...
- nginx 下 php 无法执行,虚拟主机 无法使用
检查目录下的.ini文件 有可能是因为多了个user.ini文件.这个文件在linux下可用,在window下不可用. windows下删掉这个文件后记得重启一下nginx.不然不会生效. 参考:ht ...
- Centos7.03搭建JDK、Tomcat、MySql环境
本人linux服务器配置是:centos_7_03_64_20G_xdragon_20171025.vhd 公网IP:106.14.14.224 内存:2GB SecureCRT8.0:https:/ ...
- Git本地分支和远程分支关联
转载:https://blog.csdn.net/cherishhere/article/details/52606884 转载:https://blog.zengrong.net/post/1746 ...
- Bootstrap3基础 btn-primary/warning... 三类按钮的六种样式
内容 参数 OS Windows 10 x64 browser Firefox 65.0.2 framework Bootstrap 3.3.7 editor ...
- 如何合并ts文件?
答: 使用ffmpeg工具,使用方法如下: ffmpeg -i <m3u8 file name> <output file name> 注意:要先将m3u8文件中描述的ts文件 ...
- shell编程(四)之循环控制语句(for,while,until,break,continue,case)
for循环 语法:for NAME in LIST; do 循环体 done 列表生成方式:1.整数列表 {start...end} $(seq,[start [step]] end)2.glob / ...
- Nacos整合Spring Cloud Gateway实践
Spring Cloud Gateway官网:http://spring.io/projects/spring-cloud-gateway Eureka1.0的问题和Nacos对比:https://w ...
- Visual Studio Code配置Python开发环境
1.安装Python插件 在VScode界面按Crtl+Shift+P或者F1 输入ext install 直接安装Python,也就是点击它,然后等待,安装好后会提示你重启 2.配置运行Python ...