ASP.NET Core 如何上传单个文件

来源:互联网 发布:ubuntu搭建hadoop 编辑:程序博客网 时间:2024/06/05 04:40

ASP.NET Core 如何上传单个文件

分为以下三个步骤:

  • 设置Form属性
  • 修改Controller
  • 设置Action处理POST请求

第一步:设置Form属性

<form id="form1" action="/[Controller]/[Action]" enctype="multipart/form-data" method="post" name="form1">    <input name="fileinput" type="file" /></form>

第二步:修改Controller
1.在Controller文件中添加引用

using Microsoft.AspNetCore.Hosting;

2.为Controller类添加私有成员

private IHostingEnvironment hostingEnvironment;

3.在构造函数中为成员赋值

public [Controller](IHostingEnvironment env){    this.hostingEnvironment = env;}

第三步:设置Action处理POST请求

[HttpPost]public IActionResult [Action](IFormFile fileinput){    // 文件大小    long size = 0;    // 原文件名(包括路径)    var filename = ContentDispositionHeaderValue.Parse(fileinput.ContentDisposition).FileName;    // 扩展名    var extName = filename.Substring(filename.LastIndexOf('.')).Replace("\"", "");    // 新文件名    string shortfilename = $"{Guid.NewGuid()}{extName}";    // 新文件名(包括路径)    filename = hostingEnvironment.WebRootPath + @"\upload\" + shortfilename;    // 设置文件大小    size += signature.Length;    // 创建新文件    using (FileStream fs = System.IO.File.Create(filename))    {        // 复制文件        signature.CopyTo(fs);        // 清空缓冲区数据        fs.Flush();    }}
0 0
原创粉丝点击