在 .Net Core 中上传图片为什么这段代码不起作用?
Upload images in .Net Core Why this code not work?
我在使用 postman 测试 api 时遇到问题。当我尝试 post 图像时,我的反应是: "message": "Something went wrong. Please contact support!", "statusCode": 400 该请求只是创建一个文件夹 usersImages.
[HttpPost("{username}")]
public IActionResult UploadPhoto(string username, [FromForm] IFormFile photo)
{
try
{
var user = _userService.GetCurrentUser(username);
if (user == null)
return NotFound();
var path = Path.Combine(_hosting.WebRootPath, "usersImages");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var fileName = Guid.NewGuid().ToString() + Path.GetExtension(photo.FileName);
var filePath = Path.Combine(path, fileName);
photo.CopyTo(new FileStream(filePath, FileMode.Create));
user.ImageUrl = fileName;
_userService.UpdateUser(user);
return Ok(user);
}
catch (Exception e)
{
var error = new ErrorViewModel("Something went wrong. Please contact support!", HttpStatusCode.BadRequest);
return new JsonResult(error) { StatusCode = error.StatusCode };
}
}
删除文件上传变量的 [FromForm]
属性。虽然上传是表单的一部分,但文件上传是一种特殊情况,其中的数据不包含在序列化表单中,而是存储在多部分表单元素的单独部分中。