How to pass a File JS object to Rails controller - javascript

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?

Related

sending data in correct format from react to node

I have a date object in my state coming from a react-datepicker component.
Sat Aug 28 2021 18:00:00 GMT+0530 (India Standard Time)
On Submit I am trying to pass this to my Node backend
try {
const responseData = await sendRequest('http://localhost:5000/challenge/createChallenge', 'POST',
JSON.stringify({
location: selectedOption,
format: selectedOption1,
date: selectedDate,
opponent: props.initialValues
}),
{
'Content-Type': 'application/json',
Authorization: 'Bearer ' + auth.token
})
Using Stringify, it loses its form. The date loses 5.5 hours and becomes a string.
date: '2021-08-24T12:30:00.000Z'
how do I preserve the original IST format while sending it across? I tried removing the Json.stringify but it keeps erroring me out.
I think if you send a date object to backend as below, your problem will be sorted out
date: new Date(yourDate)
and remove that JSON.stringify.
Not sure if this is the right solution but I passed the data with to.String() and its now getting received accurately in NODE. Thanks.
JSON.stringify({
location: selectedOption,
format: selectedOption1,
date: selectedDate.toString(),
opponent: props.initialValues
}),

How to implement New FormData() for Array data from Object to do the POST method using Axios, ReactJs?

On the backend I use multer to upload multiple files / images, I have tried using Postman and it works. but when i apply it on the frontend using reactjs, i am confused
sample case:
state = {
name: 'product1',
price: '200',
images: [{name: "1.png", lastModified: 1593401931873, lastModifiedDate: Mon Jun 29 2020 10:38:51 GMT+0700 (Waktu Indochina), webkitRelativePath: "", size: 176924},
{name: "2.png", lastModified: 1593401931873, lastModifiedDate: Mon Jun 29 2020 10:38:51 GMT+0700 (Waktu Indochina), webkitRelativePath: "", size: 176924}],
files: [{name: "1.zip", lastModified: 1593401931873, lastModifiedDate: Mon Jun 29 2020 10:38:51 GMT+0700 (Waktu Indochina), webkitRelativePath: "", size: 176924},
{name: "2.zip", lastModified: 1593401931873, lastModifiedDate: Mon Jun 29 2020 10:38:51 GMT+0700 (Waktu Indochina), webkitRelativePath: "", size: 176924}],
}
handleSubmit = () => {
const { name, price, images, files} = this.state
const body = new FormData()
body.append('name', name)
body.append('price', price)
images.map((file, i) => body.append('images[i]', file[i])) // not work
files.map((file, i) => body.append('files[i]', file[i])) // not work
axios.post(`http://localhost:3000/api/v1/add`, body)
.then((res) => res.data.data)
// result {"name":"roduct1","price":"200","images":[{},{}],"files":[{},{}]}
}
You can do the POST request through axios in this way:
var bodyFormData = new FormData();
bodyFormData.set('userName', 'Fred');
bodyFormData.append('image', imageFile);
axios({
method: 'post',
url: 'myurl',
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
Also its observed many times that localhost does not work with axios. Instead you need to use IP address. If suppose your IP address is 192.23.43.45 than URL becomes http://192.23.43.45:3000/api/v1/add . So, you can try this approach

How to add imported image to formData

I need to send the imported image as a file. I try to add it into new File() but it will not recognize the type and correct size of image and i can't send i to backend
import img from '../image.png';
...
const image= new File([img], "img.png");
console.log(image) //
lastModified: 1590023609558
lastModifiedDate: Thu May 21 2020 05:13:29 GMT+0400 (Armenia Standard Time) {}
name: "img.png"
size: 41 //(my real file size is 124KB)
type: ""
webkitRelativePath: ""

Converting XML to JSON and output to HTML with jQuery

I'm trying to test out an idea I had but using this XML to JSON script:
https://github.com/sergeyt/jQuery-xml2json
But then take the JSON data and then output that into HTML with jQuery.
So far, I've been able to load up the data correctly and I can console.log out the JSON data which turns out to be something like this:
releases:
$: {}
matching_count: "698"
returned_count: "50"
latestModified: "1537876805"
release: Array(50)
0:
$: {}
id: "713"
headline: "Eiger BioPharmaceuticals to Participate in Investor Conferences"
released: "1537876800"
releaseDate: "Tue, 25 Sep 2018 08:00:00 -0400"
modified: "1537876805"
modifiedDate: "Tue, 25 Sep 2018 08:00:05 -0400"
1:
$: {}
id: "712"
headline: "Communications industry innovator to speak at AMEC Global Summit"
released: "1491400800"
releaseDate: "Wed, 05 Apr 2017 10:00:00 -0400"
modified: "1491400806"
modifiedDate: "Wed, 05 Apr 2017 10:00:06 -0400"
...
My JS code that I have so far is this:
var ul = $("<ul>").appendTo("body");
$.ajax({
url: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/8689/list.xml",
dataType: "xml",
success: function(response) {
json = $.xml2json(response);
console.log(json);
$(json).each(function(index, headline) {
ul.append($(document.createElement("li")).text(headline));
});
}
});
The issue is that when it renders out, all that comes back is [object Object] in a single li.
So, I know that I'm doing something incorrectly, but I'm not sure where and at what point I need to change over to get the data so I can render out the headline, releaseDate, and so on.
I've created a Codepen here:
https://codepen.io/ultraloveninja/pen/YzPRjRw
I've read that I might need to use jQuery.parseJSON but after testing that a bit, I get some errors since it's still getting in that object.Object again.
I feel that I need to drill down a bit more to get within the releases.release somehow since that's where all the data is at to be rendered out.
The response you try to loop is an object representing the xml document.
To access the releases array you have to use json["#document"].releases.release
var ul = $("<ul>").appendTo("body");
$.ajax({
url: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/8689/list.xml",
dataType: "xml",
success: function(response) {
json = $.xml2json(response);
let release = json["#document"].releases.release
$(release).each(function(index, headline) {
ul.append($(document.createElement("li")).text(headline.headline));
});
}
});
Example

Cannot get attribute size from File object in React

With input is file, I can log to console the File as
console.log(file.size)
It gives me:
File(3987) {name: "download.jpeg", lastModified: 1544914267262, lastModifiedDate: Sat Dec 15 2018 14:51:07 GMT-0800 (Pacific Standard Time), webkitRelativePath: "", size: 3987, …}
lastModified: 1544914267262
lastModifiedDate: Sat Dec 15 2018 14:51:07 GMT-0800 (Pacific Standard Time) {}
name: "download.jpeg"
size: 3987
type: "image/jpeg"
webkitRelativePath: ""
__proto__: File
However when I do console.log(e.target.files[0].size)
It does not even fire.
Full Code as requested. FIle is coming from <input onChange={(e)=>{this.handChangeFile(e.target.files[0])}}/>
this.handleChangeFile = (file) => {
console.log(typeof file)
this.setState({ thefile: file })
let fileData = new FileReader();
fileData.readAsDataURL(file);
fileData.onloadend = () => {
imageBase64 = fileData.result
if (this.state.first == true) {
this.setState({ binary: imageBase64, hide_stock: !this.state.hide_stock, first: false }, () => {
})
}
else
this.setState({ binary: imageBase64 }, () => {
})
}
}
This is my solution on jsfiddle
with jQuery: https://jsfiddle.net/huynhsamha/dqLv83zr/
with React: https://jsfiddle.net/huynhsamha/23fv1te5/
Both they are working. Can you share your code why it is not working?
jQuery
<script async src="//jsfiddle.net/huynhsamha/dqLv83zr/embed/js,html,css,result/dark/"></script>
React
<script async src="//jsfiddle.net/huynhsamha/23fv1te5/embed/js,html,css,result/dark/"></script>

Categories