简体   繁体   中英

Could not upload photo using IFormFile object in ASP.Net Core 2 with null reference expception

I tried to upload a photo using IFormFile using a postman plugin. But the API didn't get the file object from the body of the request. I tried with and without [FromBody] .

[HttpPost]
public async Task<IActionResult> Upload(int vId, IFormFile fileStream)
{
    var vehicle = await this.repository.GetVehicle(vId, hasAdditional: false);
    if (vehicle == null)
        return NotFound();
    var uploadsFolderPath = Path.Combine(host.WebRootPath, "uploads");
    if (!Directory.Exists(uploadsFolderPath))
        Directory.CreateDirectory(uploadsFolderPath);
    var fileName = Guid.NewGuid().ToString() + Path.GetExtension(fileStream.FileName);
    var filePath = Path.Combine(uploadsFolderPath, fileName);

    using (var stream = new FileStream(filePath, FileMode.Create))
    {
        await fileStream.CopyToAsync(stream);
    }

The error shows on this line :

  var fileName = Guid.NewGuid().ToString() + Path.GetExtension(fileStream.FileName); 

I figured out that it is not getting the file, while I am sending an image.jpg with the same key "fileStream" . By the way everything else works fine. I found no solution to fix this issue. If anybody can help me with this please let me know.

在此处输入图片说明

The FromBody attribute can only be used on one parameter in the signature. One option to send the int vId is by a query string and read it with the FromQuery attribute.

Try it like this

[HttpPost]
public async Task<IActionResult> Upload([FromQuery]int vId, [FromBody]IFormFile fileStream) 

Then make the POST to url api/yourController?vId=123456789 where the body contains the IFromFile

Update

As the form-data will be sent as key-value try and create a model containing the keys and read it from the body

public class RequestModel
{
    public IFormFile fileStream { get; set; }
}

Then read the model from the body

[HttpPost]
public async Task<IActionResult> Upload([FromBody]RequestModel model) 

Finally got the solution. Actually the problem was with the old version of postman Tabbed Postman - REST Client chrome extension. After trying with new postman app it worked perfectly fine. Thanks all of you who tried to solve this problem. Here is the result: enter image description here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM