简体   繁体   中英

Upload Files to ASP.NET Core. Array is always empty

I have the following Asp.Net Core 5 controller to upload files:

[HttpPost("files")]
public virtual async Task<IActionResult> Upload(IFormFile[] files) {
}

The files are being uploaded from a Javascript library...

I checked the browser console and the Request being sent is:

Request

Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryWkiZgifAgMo5d8v3
Accept: */*
Referer: http://localhost:5000/admin/files/upload
Origin: http://localhost:5000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15
X-Requested-With: XMLHttpRequest


Request Data
MIME Type: multipart/form-data
Boundary: ----WebKitFormBoundaryWkiZgifAgMo5d8v3
Request Data: 

  ------WebKitFormBoundaryWkiZgifAgMo5d8v3
  Content-Disposition: form-data; name="files[]"; filename="4e540d9d58d4bf6dd7f713e775a8f9bd 2.jpg"
  Content-Type: image/jpeg
  ------WebKitFormBoundaryWkiZgifAgMo5d8v3--

In my File Controller the array files has no item...

Any idea what I might be missing?

In my File Controller the array files has no item

Content-Disposition: form-data; name="files[]"; filename="4e540d9d58d4bf6dd7f713e775a8f9bd 2.jpg"

In your code, we can find your action method Upload accept a parameter named files , but you seems set form data key with files[] , which cause the posted files can not bound to IFormFile[] files parameter.

To fix it, you can try to modify form data key from files[] to files .

formData.append("files", imgfile);

you forgot FromForm ?

 public virtual async Task<IActionResult> Upload([FromForm] IFormFile[] files) { .. }

The problem is Redactor always sends the data key with [], eg files[].

It allows to change the name from files to something else but always adds [].

So I created a custom function... Maybe useful to someone facing the same problem.

imageUpload: function(data, files, e, upload) {
  data.append('file', files[0]);
  return fetch('/files/images', {
    method: 'POST',
    body: data
  })
  .then(response => {
    return response.json()
  })
  .then(response => {
    upload.complete(response);
  })
  .catch(response => {
    upload.complete(response);
  });
} 

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