首页 .NET/Web NetCore之Layui批量上传与单个上传Controller接口方法

NetCore之Layui批量上传与单个上传Controller接口方法

作者:胡同里的砖头 围观群众:325 更新于:2022-04-13

多个文件上传

private readonly IHostingEnvironment _hostingEnvironment;

public UploadController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public async Task<IActionResult> UploadFiles(List<IFormFile> file)
{
EditorDataResult editorResult = new EditorDataResult();
foreach (var formFile in file)
{
if (formFile.Length > 0)
{
FileInfo fi = new FileInfo(formFile.FileName);
string ext = fi.Extension;
var orgFileName = fi.Name;
var newFileName = Guid.NewGuid() + ext;
var uploads = Path.Combine(_hostingEnvironment.WebRootPath, "你想要上传到文件夹");
var filePath = Path.Combine(uploads, newFileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
}
editorResult.code = 0;
}
else
{

editorResult.code = 1;
}
}
JavaScriptSerializer jss = new JavaScriptSerializer();
string data = jss.Serialize(editorResult);//转换为Json格式!
return Json(data);
}
单个文件上传
private readonly IHostingEnvironment _hostingEnvironment;

public UploadController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}



public async System.Threading.Tasks.Task<IActionResult> index(IFormFile file)
{
int code = 0;
string mgf = "上传成功";
bool success = true;
string url = "";
try
{
FileInfo fi = new FileInfo(file.FileName);
string ext = fi.Extension;
var orgFileName = fi.Name;
var newFileName = Guid.NewGuid() + ext;
var uploads = Path.Combine(_hostingEnvironment.WebRootPath, "file");
var filePath = Path.Combine(uploads, newFileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
url = string.Format("file/{0}", newFileName);
}
catch(Exception ex) {
code = 1;
mgf = "上传失败";
success = false;
}
var result = new { code, mgf, success, url };
return Ok(result);
}

  • 本文标题: NetCore之Layui批量上传与单个上传Controller接口方法
  • 文章分类:【.NET/Web】
  • 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.
留言评论
站点声明:
1、本站【胡同里的砖头】个人博客,借鉴网上一些博客模板,取其各优点模块自行拼装开发,本博客开发纯属个人爱好。
2、所有笔记提供给广大用户交流使用,可转载,可复制,纯个人开发所遇问题锦集记录使用
Copyright © huzlblog.com All Rights Reserved. 备案号:苏ICP备2021056683号-8