简体   繁体   中英

Single file upload with FormData

I want to upload a single file with this code:

let formData = new FormData();
let file = this.file[0];
formData.append("file", file);

Normally I use this piece of code because when I upload multiple files:

 let formData = new FormData();
  for (let i = 0; i < data.files.length; i++) {
    let file = data.files[i];
    consol
    formData.append("files[" + i + "]", file);
  }

But with the single file upload the formData variable stays empty after I append the file. When I console.log the file variable it shows me this:

File {name: "2020_03_17 21_53 Office Lens (1).jpg", lastModified: 1587394084978, lastModifiedDate: Mon Apr 20 2020 16:48:04 GMT+0200 (Central European Summer Time), webkitRelativePath: "", size: 306890, …}
lastModified: 1587394084978
lastModifiedDate: Mon Apr 20 2020 16:48:04 GMT+0200 (Central European Summer Time) {}
name: "2020_03_17 21_53 Office Lens (1).jpg"
size: 306890
type: "image/jpeg"
webkitRelativePath: ""

Why is this file not appended to the FormData?

The contents of a file (in form of bytes) is never shown in console.log.
if you're able to see the file.size it means that the file is present in the formdata object.

To test this - try sending this formdata to the API and use httpRequest.FormData[0] to receive it - and you''ll find that your file has been sent to the api

Refer - https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

I guess in the code you need "files" instead of "file". And also you can check what are you actually referring by "this"

let formData = new FormData();
let file = this.files[0];
formData.append("file", file);

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