Formdata image file does not fall into API call

I use JavaScript to create an API call and send it to the corresponding Asp.Net Core function.

JavaScript:

function fileSubmit() {
        var data = document.getElementById("myFile").files; //it should be noted that this successfully catches the file.
        var formData = new FormData();        
        formData.append("files", data);         

        var url = "http://localhost/api/Surveys/123456/Units/987654/Images";        
        var xhr = new XMLHttpRequest();
        xhr.open("POST", url, true);        
        xhr.setRequestHeader("Content-type", "image/jpeg"); 
        xhr.send(formData);       
}

.Net Core:

[HttpPost]
[Route("{Id:int:min(1)}/Units/{unitId:int:min(1)}/Images")]
[ProducesResponseType(typeof(IAPIResponse2<UploadImagesResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(IAPIResponse2<UploadImagesResponse>), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> UploadImages([FromForm, Required] IList<IFormFile> files)
{
       //do stuff
}

I can create and send an API call and it is caught by the Asp.Net function, but the parameter is filesempty. As far as I know, the list of files has been successfully added to the object formDatain the JavaScript function.

What am I missing?

+4
source share
1 answer

There are two problems with the JavaScript code above:

  • filesnot sent correctly. If you look at the query, you will see it a little confusing and include [object FileList]as part of the body.

To solve this problem, you will want to iterate the files and add them separately:

var files = document.getElementById("myFile").files;
var formData = new FormData();

for (var i = 0; i < files.length; i++) {
    formData.append("files", files[i]);
}

, :

var files = document.getElementById("myFile").files;
var formData = new FormData();

formData.append("files", files[0]);
  1. Content-Type .

, setRequestHeader. Content-Type XHR multipart/form-data (. RFC Content- ).

, , , .

, , Content-Type . , , .

+2

Source: https://habr.com/ru/post/1683445/


All Articles