.net core webapi 文件上传
技术架构:.net core + antd vue
直接上代码!!!
1.后端代码实现方法(这种写法仅支持单个文件上传):
public IActionResult uploadFileForAsset(IFormFile file)
{
try
{
// 服务器将要存储文件的路径
string path = "/assetImg/";
//var Folder = AppDomain.CurrentDomain.BaseDirectory + path; //项目默认路径
var Folder = "C:/adminFile" + path;
if (Directory.Exists(Folder) == false)//如果不存在就创建file文件夹
{
Directory.CreateDirectory(Folder);
}
StreamReader reader = new StreamReader(file.OpenReadStream());
String content = reader.ReadToEnd();
String name = file.FileName; // 获取文件名
String filename = Folder + name;
if (System.IO.File.Exists(filename))
{
System.IO.File.Delete(filename);
}
using (FileStream fs = System.IO.File.Create(filename))
{
// 复制文件
file.CopyTo(fs);
// 清空缓冲区数据
fs.Flush();
}
return new JsonResult(new { success = true, msg = "上传成功!", result = path+name });
}
catch (Exception ex)
{
return new JsonResult(new { success = false, msg = "上传失败!", result = ex.Message });
}
}
2.前端页面实现:
<template>
<a-upload name="file" :multiple="true" action="" :headers="headers" :customRequest="uploadFileForAsset" :showUploadList="false">
<a-button> <a-icon type="upload" />上传</a-button>
</a-upload>
</template>
data() {
return {
headers: {
authorization: 'authorization-text',
},
},
methods: {
uploadFileForAsset(data) {
const formData = new FormData()
formData.append('file', data.file)
postAction(this.url.uploadFileForAsset, formData).then((res) => {
if (res.success) {
this.$message.success(res.msg)
} else {
this.$message.error(res.msg)
}
})
},
}
3.上传效果: