多个文件上传
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】
- 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.