Upload files and JSON in ASP.NET Core Web API

前端 未结 8 1229
夕颜
夕颜 2020-11-29 18:12

How can I upload a list of files (images) and json data to ASP.NET Core Web API controller using multipart upload?

I can successfully receive a list of files, upload

相关标签:
8条回答
  • 2020-11-29 18:37

    Following the excellent answer by @bruno-zell, if you have only one file (I didn't test with an IList<IFormFile>) you can also just declare your controller as this :

    public async Task<IActionResult> Create([FromForm] CreateParameters parameters, IFormFile file)
    {
        const string filePath = "./Files/";
        if (file.Length > 0)
        {
            using (var stream = new FileStream($"{filePath}{file.FileName}", FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
        }
    
        // Save CreateParameters properties to database
        var myThing = _mapper.Map<Models.Thing>(parameters);
    
        myThing.FileName = file.FileName;
    
        _efContext.Things.Add(myThing);
        _efContext.SaveChanges();
    
    
        return Ok(_mapper.Map<SomeObjectReturnDto>(myThing));
    }
    

    Then you can use the Postman method shown in Bruno's answer to call your controller.

    0 讨论(0)
  • 2020-11-29 18:38

    I'm working with Angular 7 on the front-end, so I make use of the FormData class, which allows you to append strings or blobs to a form. They can be pulled out of the form in the controller action using the [FromForm] attribute. I add the file to the FormData object, and then I stringify the data I wish to send together with the file, append it to the FormData object, and deserialize the string in my controller action.

    Like so:

    //front-end:
    let formData: FormData = new FormData();
    formData.append('File', fileToUpload);
    formData.append('jsonString', JSON.stringify(myObject));
    
    //request using a var of type HttpClient
    http.post(url, formData);
    
    //controller action
    public Upload([FromForm] IFormFile File, [FromForm] string jsonString)
    {
        SomeType myObj = JsonConvert.DeserializeObject<SomeType>(jsonString);
    
        //do stuff with 'File'
        //do stuff with 'myObj'
    }
    

    You now have a handle on the file and the object. Note that the name you provide in the params list of your controller action must match the name you provide when appending to the FormData object on the front-end.

    0 讨论(0)
提交回复
热议问题