1. 说明
-
异步上传文件报404
- uploadfile_404.png
-
后台代码如下
[HttpPost]
public async Task<MessageModel<string>> UploadFileAsync(IFormFile file)
{
var fileName = Path.GetRandomFileName() + Path.GetExtension(file.FileName);
//拼接完整的文件存储路径
var filePath = Path.Combine(_environment.ContentRootPath, fileName);
using (var fs = System.IO.File.Create(filePath))
{
await file.CopyToAsync(fs);
}
return new MessageModel<string>()
{
success = true,
msg = "创建成功",
response = fileName
};
}
2. 解决
- 我也是百度到一位大神遇到的同样情况,如果是异步上传(net core 3.0 之后),方法名后不要带有 Async (有点神奇)
- 修改代码
[HttpPost]
public async Task<MessageModel<string>> UploadFile([FromServices] IHostEnvironment env, UserInfo input)
{
try
{
string filename = string.Empty;
filename = Path.Combine("file", Guid.NewGuid().ToString() + input.HeadPortrait);
using (var stream = new FileStream(Path.Combine(env.ContentRootPath,filename),FileMode.CreateNew))
{
}
var entity = _mapper.Map<UserInfo>(input);
entity.CreateTime = DateTime.Now;
await _userInfoService.InsertAsync(entity, true);
return new MessageModel<string>()
{
success = true,
msg = "创建成功",
response = filename
};
}
catch (Exception ex)
{
return new MessageModel<string>()
{
success = false,
msg = "异常",
response = null
};
}
}
- 上传成功
-
http://127.0.0.1:5003/api/UserInfo/UploadFile
200_成功.png
网友评论