'How to pass a File JS object to Rails controller

I have a JS file object (like the one below) that I'd like to pass to my rails controller.

File {name: 'undefined', lastModified: 1652457009460, lastModifiedDate: Fri May 13 2022 10:50:09 GMT-0500 (Central Daylight Time), webkitRelativePath: '', size: 582843, …}lastModified: 1652457009460lastModifiedDate: Fri May 13 2022 10:50:09 GMT-0500 (Central Daylight Time) {}name: "undefined"size: 582843type: "image/png"webkitRelativePath: ""[[Prototype]]: FilelastModified: (...)lastModifiedDate: (...)name: (...)webkitRelativePath: (...)constructor: ƒ File()Symbol(Symbol.toStringTag): "File"size: (...)type: (...)get lastModified: ƒ lastModified()get lastModifiedDate: ƒ lastModifiedDate()get name: ƒ name()get webkitRelativePath: ƒ webkitRelativePath()[[Prototype]]: Blob I'm trying to pass it inside a data object like this:

data: { someData: '', myFile: JSON.stringify(myFile)}

Unfortunately that results in passing an empty object like below:

data: { someData: '', myFile: {}}

If I try to pass it without stringifying it I get:

serialize.js:66 Uncaught TypeError: Illegal invocation

The only way I've been able to do it is via FormData() like:

const formData = new FormData(); formData.append("file", myFile); However, I cannot use formData in this occasion for other reasons.

Can you provide some guidance on what other ways are there to pass this data?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source