Search code examples
c#.netimage-uploading

Upload images in .Net Core Why this code not work?


I have a problem with testing the api with postman. When I try to post image my response is: "message": "Something went wrong. Please contact support!", "statusCode": 400 The request just make a folder 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 };
    }
}

Solution

  • Remove the [FromForm] attribute on your file upload variable. Although the upload is part of the form, the file uploads are a sort of special case in which the data for them isn't contained in the serialized form, and are stored in a separate section of the multi-part form element.