在 ASP.NET Core 中上传文件

vs2019 选择文件后,调试停止问题
工具 -> 选项 -> 项目和解决方案 -> Web项目 -> 浏览器窗口关闭时停止调试器(s) 复选√ 去掉

1、单个文件
IFormFile

2、多个文件的集合:
IFormFileCollection
IEnumerable<IFormFile>
成员列表<IFormFile>

3、Postman请求

 


ASP.NET Core Controller 文件

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication.Controllers
{
public class TestController : Controller
{
public IActionResult Index()
{
return View();
}

/// <summary>
/// from表单submit提交上传,通过IFormFile参数获取上传文件信息【OK】
/// el-upload【获取不到参数】
/// </summary>
/// <param name="files"></param>
/// <returns></returns>
[HttpPost("upload_avatar")]
public async Task<IActionResult> UploadAvatar([FromForm] List<IFormFile> files)
{
long size = files.Sum(f => f.Length);

if (files.Count < 1)
return Ok(new { code = -1, msg = "没有上传文件", data = "" });

//当前程序路径
var path = Directory.GetCurrentDirectory();

foreach (var formFile in files)
{
if (formFile != null && formFile.Length > 0)
{
var filePath = Path.GetTempFileName();

var filePath1 = Path.Combine("", Path.GetRandomFileName());

#region 图片文件的条件判断

//没有后缀扩展名的文件名
var currentPictureWithoutExtension = Path.GetFileNameWithoutExtension(formFile.FileName);

//文件后缀
var fileExtension = Path.GetExtension(formFile.FileName).ToUpper();

//判断后缀是否是图片
const string fileFilt = ".gif|.jpg|.jpeg|.png";
if (fileExtension == null)
return new JsonResult(new { code = "-1", msg = "上传的文件没有后缀" });

if (fileFilt.IndexOf(fileExtension.ToLower(), StringComparison.Ordinal) <= -1)
return new JsonResult(new { code = "-1", msg = "请上传jpg、png、gif格式的图片" });

//判断文件大小
long length = formFile.Length;
if (length > 1024 * 1024 * 2) //2M
return new JsonResult(new { code = "-1", msg = "上传的文件不能大于2M" });

#endregion

#region 上传图片
using (var stream = System.IO.File.Create(filePath))
{
await formFile.CopyToAsync(stream);
}
#endregion
}
}
//return Ok();
return Ok(new { count = files.Count, size });
}

/// <summary>
/// from表单submit提交上传,通过IFormCollection参数获取上传文件信息【OK】
/// el-upload【OK】
/// </summary>
/// <param name="files"></param>
/// <returns></returns>
[HttpPost("up_avatar")]
public async Task<IActionResult> UpAvatar([FromForm] IFormCollection formCollection)
{
var fileFolder = Path.Combine("", "wwwroot/upload");

//定义图片数组后缀格式
string[] LimitPictureType = { ".JPG", ".JPEG", ".GIF", ".PNG", ".BMP" };

FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;
foreach (IFormFile file in fileCollection)
{
//获取图片后缀是否存在数组中
string currentPictureExtension = Path.GetExtension(file.FileName).ToUpper();
if (LimitPictureType.Contains(currentPictureExtension))
{
var fileName = $"{DateTime.Now.ToString("yyyyMMddHHmmss")}{Path.GetExtension(file.FileName)}";
var filePath = Path.Combine(fileFolder, fileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
else
{
//return Json(new { status = -2, message = "请上传指定格式的图片", data = hash });
}
}
return Ok();
}

/// <summary>
/// from表单submit提交上传,通过IFormFileCollection参数获取上传文件信息【OK】
/// el-upload【获取不到参数】
/// </summary>
/// <param name="formCollection"></param>
/// <returns></returns>
[HttpPost("batch_upload_avatar")]
public async Task<IActionResult> BatchUploadAvatar([FromForm] IFormFileCollection files)
{
long size = files.Sum(f => f.Length);

var fileFolder = Path.Combine("", "wwwroot/upload");

if (!Directory.Exists(fileFolder))
Directory.CreateDirectory(fileFolder);

if (files.Count > 0)
{
foreach (IFormFile file in files)
{
var fileName = $"{DateTime.Now.ToString("yyyyMMddHHmmss")}{Path.GetExtension(file.FileName)}";
var filePath = Path.Combine(fileFolder, fileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
}
return Ok();
}

/// <summary>
/// AJAX请求上传,通过Request.Form.Files获取上传文件信息【OK】
/// el-upload【OK】
/// </summary>
/// <param name="files"></param>
/// <returns></returns>
[HttpPost("single_upload_avatar")]
public async Task<IActionResult> SingleUploadAvatar()
{
#region 单个文件上传
var file = Request.Form.Files[0];

string fileName = string.Empty;
//using (FileStream fs = System.IO.File.Create(fileName))
//{
// file.CopyTo(fs);
// fs.Flush();
//}
#endregion

#region 批量上传
var files = Request.Form.Files;
string filePhysicalPath = string.Empty;
foreach (var itemFile in files)
{
if (file.Length > 0)
{
var fName = System.Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);//文件名+文件后缀名
using (var stream = new FileStream(filePhysicalPath + fileName, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
}
#endregion
return Ok();
}

[HttpPost("upload_base64")]
public ActionResult UploadBase64(string fileBase64, string fileName)
{
return Ok();
}
}
}
*
JavaScript 方式

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="lib/jquery/dist/jquery.js"></script>
<script>

$(document).ready(function () {
$("#btn_fileUpload").click(function () {
var fileUpload = $("#files").get(0);
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
$.ajax({
type: "POST",
url: 'http://localhost:55084/single_upload_avatar',
contentType: false,
processData: false,
data: data,
success: function (data) {
console.log(JSON.stringify(data));
},
error: function () {
console.log(JSON.stringify(data));
}
});
});
})

//前端第一种提交方式
function uplpadfile() {
//获取表单的数据
var formdata
var file = $("#files").get(0);
var files = file.files;
var formdata = new FormData();
for (var i = 0; i < files.length; i++) {
formdata.append("files", files[i]);
}

$.ajax({
type: 'Post',
data: formdata,
contentType: false,
processData: false,
url: "http://localhost:55084/upload_avatar",
success: function (result) {
if (result.Success) {
} else {
alert('提交失败,重新尝试提交');
}
}
})
};
</script>
</head>
<body>
<h3>1、ajax上传</h3>
<form enctype="multipart/form-data">
<input type="file" id="files" name="files" placeholder="file" multiple>
<input type="button" id="btn_fileUpload" value="提交">
</form>
<br /><br /><br />
<h3>2</h3>
<form enctype="multipart/form-data">
<input type="file" name="files" id="files" value="选择需要上传的文件" multiple />
<input type="button" value="提交" onclick="uplpadfile()">
</form>
<br /><br /><br />
<h3>3、form 表单标签 submit 上传</h3>
<h6>表单提交上传 通过IFormFile参数获取上传文件信息</h6>
<h6>AJAX请求上传,通过Request.Form.Files获取上传文件信息</h6>
<form method="post" enctype="multipart/form-data" action="/batch_upload_avatar">
<div class="form-group">
<div class="col-md-10">
<p>Upload one or more files using this form:</p>
<input type="file" id="files" name="files" multiple />
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input type="submit" value="服务器方式上传" />
</div>
</div>
</form>
</body>
</html>
*
Vue el-upload 方式

<template>
<el-upload
class="avatar-uploader"
action="http://localhost:60548/api/v1.0/users/upload_avatar"
:headers="token"
:data="{ user_code: 666 }"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</template>
<script>
import { getToken } from "@/utils/auth";

export default {
data() {
return {
token: { Authorization: `Bearer ${getToken()}` }
};
},
};
</script>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409eff;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>

<script>
export default {
data() {
return {
imageUrl: "",
};
},
methods: {
handleAvatarSuccess(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
},
beforeAvatarUpload(file) {
const isLt2M = file.size / 1024 / 1024 < 2;
return isLt2M;
},
},
};
</script>