简体   繁体   中英

Formdata image file isn't being caught by API call

I am using JavaScript to create an API call and send it to a 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 am able to create and send the API call and it is caught by the Asp.Net function, but the files parameter is empty. The file list is successfully appended to the formData object in the JavaScript function, as far as I know.

What am I missing?

There are two problems with your JavaScript code above:

  1. files is being sent incorrectly. If you look at the request, you'll see it's a bit confused and includes [object FileList] as part of the body.

To solve this issue, you'll want to iterate through the files and add them individually:

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

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

If you are just sending the one file, you could simplify this:

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

formData.append("files", files[0]);
  1. You should not set the Content-Type header when making the request.

To solve this issue, simply remove your call to setRequestHeader . The Content-Type header will be set by the XHR process to be multipart/form-data with boundaries (see the RFC for the Multipart Content-Type).

Each part starts with an encapsulation boundary, and then contains a body part consisting of header area, a blank line, and a body area.

Due to the way this is structured, the Content-Type is specified on a per-file basis. If you are interested, have a look at the request in the developer tools once you've made the changes I have detailed.

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