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=" ...
随机推荐
- API网关性能比较:NGINX vs. ZUUL vs. Spring Cloud Gateway vs. Linkerd(转)
前几天拜读了 OpsGenie 公司(一家致力于 Dev & Ops 的公司)的资深工程师 Turgay Çelik 博士写的一篇文章(链接在文末),文中介绍了他们最初也是采用 Nginx 作 ...
- 12: xlrd 处理Excel文件
1.1 xlrd处理.xlsx 文件 1.xlrd常用方法 #!/usr/bin/python # coding:utf-8 # 用xlrd读取Excel文件基本用法 import sys impor ...
- Python3.6.2在线安装pymysql模块
我是一个python新手刚才使用python写邮件发送代码的时候想着需要连接数据库, 下面的安装步骤 python -m pip install pymysql PS C:\Users\hp> ...
- 如何获取sdcard的总容量
activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android& ...
- linux任务计划及周期性任务计划
相关命令:at.batch.cron.mailx 未来某时间执行一次任务:at, batch 周期性运行某任务: cron 一.未来某时间执行一次任务:at命令 at, batch, atq, atr ...
- delimiters 插值 选项
delimiters差值选项vue默认是{{}},这个选项可以把这个差值形式进行改变,这里讲,默认插值改成${} html <div id="app"> <div ...
- Introducing GitFlow
Introducing GitFlow What Is GitFlow? GitFlow is a branching model for Git, created by Vincent Driess ...
- 51nod1057-N的阶乘(大数乘法巧解)
这道大数乘法开始我是想套板子模拟的..然后就发现2/3的例子都wa了.(惊了).然后在思考后发现n2的板子的确过不了这么多的大数.(不看题的下场).所以,我在网上发现了分块求大数的方法.%%% 思路来 ...
- 以结算价交易TAS和以市价交易TAM
CME Group的合约规格中提到TAS和TAM交易,如:Gold Futures Contract Specs Gold 期货 合约规格 Trading at Settlement (TAS) is ...
- Latex: 解决 The gutter between columns is x inches wide (on page x), but should be at least 0.2 inches. 问题
参考: Sample_WCCI.tex Latex: 解决 The gutter between columns is x inches wide (on page x), but should be ...