NET5配合vue3图片上传
后端函数
/// <summary>
/// 上传文件
/// </summary>
/// <param name="files">文件流</param>
/// <returns></returns>
[HttpPost]
public void FileSave(List < IFormFile > files)
{
//返回的文件地址
List < string > filenames = new List < string > ();
DateTime now = DateTime.Now;
//文件存储路径
string filePath = string.Format("/Uploads/{0}/{1}/{2}/", now.ToString("yyyy"), now.ToString("yyyyMM"), now.ToString("yyyyMMdd"));
//获取当前web目录
var webRootPath = "File/";;
if (!Directory.Exists(webRootPath + filePath))
{
Directory.CreateDirectory(webRootPath + filePath);
}
try
{
foreach(var item in files)
{
if (item != null)
{
#
region 图片文件的条件判断
//文件后缀
string fileExtension = Path.GetExtension(item.FileName);
//判断后缀是否是图片
const string fileFilt = ".gif|.jpg|.jpeg|.png";
if (fileExtension == null)
{
break;
//return Error("上传的文件没有后缀");
}
if (fileFilt.IndexOf(fileExtension.ToLower(), StringComparison.Ordinal) <= -1)
{
break;
//return Error("请上传jpg、png、gif格式的图片");
}
//判断文件大小
long length = item.Length;
if (length > 1024 * 1024 * 2) //2M
{
break;
//return Error("上传的文件不能大于2M");
}#
endregion
string strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
string strRan = Convert.ToString(new Random()
.Next(100, 999)); //生成三位随机数
string saveName = strDateTime + strRan + fileExtension;
//插入图片数据
using(FileStream fs = System.IO.File.Create(webRootPath + filePath + saveName))
{
item.CopyTo(fs);
fs.Flush();
}
filenames.Add(filePath + saveName);
}
}
}
catch (Exception ex)
{
//这边增加日志,记录错误的原因
//ex.ToString();
}
}
前端使用
handleUploadImage函数
files md插件已经获取到图片文件
async function handleUploadImage(_event: any, insertImage: any, files: any) {
const file = files
const formData = new FormData()
for (var i = 0; i < file.length; i++) {
formData.append('files', files[i])
}
await common.uploadImg(formData).then((res: any) => {
insertImage({
url: res.data,
desc: files[0].name
// width: 'auto',
// height: 'auto',
})
})
}
axios uploadImg函数
static async uploadImg(data: FormData) {
return request({
url: "/api/v1/common/upload-file",
method: 'post',
headers: { "Content-Type": "multipart/form-data" },
data: data
})
}
axios 增加判断
if (config.method !== 'post' && config.headers['Content-Type'] !== 'multipart/form-data') {
config.data = qs.parse(config.data);
}
标签:files,string,filePath,上传,ToString,vue3,NET5,data
From: https://www.cnblogs.com/ouyangkai/p/16660455.html