上传文件踩过的坑
前端代码
<input type="file" v-on:change="onFileChange" />
<button @click="uploadfile">点击上传</button>
实例化 FormData
const formData = new FormData();
把文件添加进 formData 注意这里的 formFile 一定要和后端的一致,否则会报API请求地址错误(bad request 意思是 "错误的请求";)
// 这里formFile一定要对应后端api传入的名字 formFile,否则会报请求地址错误
const onFileChange = (file: any) => {
formData.append('formFile', file.target.files[0])
}
使用axios上传文件到服务器
const uploadfile = () => {
axios.post("http://localhost:5207/FileUpload/UploadFile", formData).then((response) => {
console.log(response.data);
})
}
后端代码
APIController
[HttpPost]
public string UploadFile(IFormFile formFile)
{
var path = @"Z:/";
var rootpath = @"http://localhost:8016/";
var fileext = ".txt|.exe|.jpg";
return fileUploadHelper.SaveFile(formFile, path, rootpath, fileext);
}
具体实现类
public string SaveFile(IFormFile file, string savepath, string rootpath, string fileext)
{
// 判断是否存在文件夹
if (!Directory.Exists(savepath))
{
Directory.CreateDirectory(savepath);
}
// 获取文件扩展名
var fileExt = Path.GetExtension(file.FileName);
// 判断文件是否为空
if (file == null) return "111";
// 判断传入的扩展名是否为空,并且包含在内
if (fileext != null && fileext.IndexOf(fileExt.ToLower()) <= -1) return "222";
// long length = file.Length;
// if (length > Convert.ToInt64(configuration["MaxFileSize"])) return "超出文件大小";
// 创建hash文件名
var hash = SHA1.Create();
var hashBytes = hash.ComputeHash(file.OpenReadStream());
var saveName = BitConverter.ToString(hashBytes).Replace("-", "") + fileExt;
FileInfo fileInfo = new FileInfo(savepath + saveName);
if (!fileInfo.Exists)
{
using FileStream fs = File.Create(savepath + saveName);
file.CopyTo(fs);
fs.Flush();
}
savepath = $"{rootpath}{saveName}";
return savepath;
}