我有下面的代码,您可以在下面看到。
如果用户上传的文件不是某个文件扩展名,或者文件太大,那么我希望控制器向用户返回错误消息。
现在,我只是返回一个一般的错误请求。
有没有一种方法可以让控制器拒绝上传,同时在浏览器中向用户显示适当的错误消息?
[HttpPost]
public async Task<IActionResult> UploadUserFiles([FromForm] IFormFile gamerFile)
{
int maxFileSize = 52428800; //50MB
var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".pdf", ".odt", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".rtf", ".txt" };
if(gamerFile.Length > maxFileSize)
{
return BadRequest();
// return an error to user saying max file size exceeded
}
if(!allowedExtensions.Contains(Path.GetExtension(gamerFile.FileName)))
{
return BadRequest();
// return an error to user saying the file was not a valid type
}
var filePath = Path.Combine(@"R:\gamer\screens\uploadedMediaFiles", gamerFile.FileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await gamerFile.CopyToAsync(fileStream);
}
return Ok();
}
return BadRequest("Message")
可以将字符串作为参数添加到BadRequest
方法。