分享一个可多个文件同时上传、断点续传,并实时反馈上传进度的 Asp.Net core 组件。
服务器端
引用 nuget 包:JMS.FileUploader.AspNetCore
然后启用上传组件:
app.UseAuthorization();
app.MapControllers();
//启用上传组件,并限制单个文件最大100M
app.UseJmsFileUploader(1024*102400);
app.Run();
在 Controller 里面,写个 Test 函数,处理上传的文件:
[ApiController]
[Route("[controller]/[action]")]
public class MainController : ControllerBase
{
[HttpPost]
public string Test([FromBody] object body)
{
var customHeader = Request.Headers["Custom-Header"];
//临时文件路径
var filepaths = Request.Headers["FilePath"];
//文件名
var filenames = Request.Headers["Name"];
return filenames;
}
}
文件上传完毕,保存在临时文件中,Request.Headers["FilePath"] 可以读取这些文件的路径,如果确定要保留这些文件,用 File.Move 把它们移到你的目标文件夹当中;
Request.Headers["Name"] 则是读取文件名。
前端
引入 jms-uploader 组件:
import JmsUploader from "jms-uploader"
html 元素:
<input id="file1" multiple type="file" />
<input id="file2" multiple type="file" />
<button onclick="upload()">
upload
</button>
<div id="info"></div>
javascript 脚本:
async function upload() {
//自定义请求头
var headers = function () {
return { "Custom-Header": "test" };
};
//提交的body
var dataBody = {
name: "abc"
};
var uploader = new JmsUploader("http://localhost:5200/main/test", [document.querySelector("#file1").files, document.querySelector("#file2").files], headers, dataBody);
uploader.setPartSize(1024);//设置分块大小,默认是102400
uploader.onUploading = function (percent, uploadedSize, totalSize) {
document.querySelector("#info").innerHTML = percent + "% " + uploadedSize + "," + totalSize;
};
var ret = await uploader.upload();
//上传完毕
alert(ret);
}