I'm trying out a bulk upload functionality where I can get user details like name, email, and profile pic (file) as fields. Upon submitting, they are sent directly to backend models and stored.
I was able to successfully send just one row of data by using Form Data object and appending all the fields including image file field. The issue comes when the uploaded data is more than 1 row. I'm not able to figure out how to send Form Data as array of objects to my backend.
I tried appending formdata to array. So something like
// Convert this
// [
// { name: 'xyz', email: 'xyz#gmai.com', img_name: 'xyz' },
// { name: 'abc', email: 'abc#gmail.com', img_name: 'abc' }
// ]
//
// to
//
// [
// { name: 'xyz', email: 'xyz#gmai.com', image: BinaryFile },
// { name: 'abc', email: 'abc#gmail.com', image: BinaryFile }
// ]
const newDataToSend = []
// append image file to appropriate row according to name
if (imageFiles && imageFiles.length > 0) {
dataToSend.forEach(row => {
const formData = new FormData();
Object.keys(row).forEach(column => {
if (column === "img_name") {
let fileObj;
for (let i = 0; i < imageFiles.length; i++) {
const file = imageFiles.item(i);
if (file && file.name.indexOf(row[column]) > -1) {
fileObj = file;
}
}
if (fileObj) {
formData.append("photo", fileObj);
}
} else {
formData.append(column, row[column]);
}
});
newDataToSend.push(formData);
});
}
This does not work. Throws error code 415 and payload is empty as well.
Are there any other solutions I can try?
could you please add the other codes you have written . possibly you may not have a submit button .
You could do JSON.stringify on the array data like shown in the code snippet:
let formdata = new FormData();
let dataArr = [data1, data2, data3];
formdata.append('dataArr', JSON.stringify(dataArr));
If you have the data in the form of an array of objects, you probably want to do something like this.
const dataToSend = [
{ firstName: 'Robin', lastName: 'Hood'},
{ firstName: 'Kavita', lastName: 'Gurav'},
{ firstName: 'Albert', lastName: 'Einstein'}
];
/** sending the data by the name 'data' */
const formData = new FormData();
formData.append('data', dataToSend);
fetch(<api endpoint>, {
method: 'POST',
body: formData
});
The backend now should be able to read the data submitted from data.
I tried this on my browser, the payload being sent is like below.
Related
It receives data from the request body in the following format. Properly I have to insert it into the database but the format is not correct.
{
name: '123',
description: 'Dev',
"item_variants[0]['name']": '23434',
"item_variants[0]['quantity']": '12334',
"item_variants[0]['unit_price']": '123123',
}
And how to transform the following format? Everyone's answers help me some ideas. Thank you
{
name: '123',
description: 'Dev',
item_variants: [
{
name: '23434',
quantity: '23434',
unit_price: '23434',
}
]
}
In express, after getting this form body you have to store this response in any variable and reformate this response after formatting you can save it into the database.
try {
let inputs = req.body;
inputs = {
name: inputs.name,
description: inputs.description,
item_variants: [
{
name: item_variants[0].name,
quantity: item_variants[0].quantity,
unit_price: item_variants[0].unit_price,
},
],
};
// NOW you can save this formatted version into the database
const result = await Product.save(inputs);
} catch (e) {
console.log(e);
}
In item_variants name, quantity, unit_price you might change digging and getting value.
This is NeutralinoJS storage API for writing JSON. Is it possible to update JSON file (push data), not just overvrite data with new JS object. How to do that???
// Javascript Object to be stored as JSON
let data = {
bucket : 'test',
content : {
item : 10
}
}
// stores the data into JSON based data store.
Neutralino.storage.putData(data,
// executes on successful storage of data
function () {
console.log('Data saved to storage/test.json');
},
// executes if an error occurs
function () {
console.log('An error occured while saving the Data');
}
);
The Neutralino.storage api takes string instead of JSON to save into local storage.
And you can create your JavaScript Objects to String Very easily, for example:
const myUser = {
name: "John Doe",
age: 19,
married: false
}
const myUserString = JSON.stringify(myUser);
console.log(myUserString); // {"name":"John Doe","age":19,"married":false}
Here you can see how we used JSON.stringify method to convert our JavaScript Object into string.
Now We Can Also Convert generated string back to our javascript object, example:
const myUserString = '{"name":"John Doe","age":19,"married":false}';
const myUser = JSON.parse(myUserString);
console.log(myUser);
So now we can easily store our Objects and arrays to local storage and easily modify them, example:
async function saveToStorage(myUser) {
let myUserString = JSON.stringify(myUser);
await Neutralino.storage.setData('myUser', myUserString);
});
async function loadFromStorage() {
let myUserString = await Neutralino.storage.getData('myUser');
let myUser = JSON.parse('myUser');
return myUser;
}
saveToStorage({
name: "John Doe",
age: 19,
married: false
}).then(async () => {
let myUser = await loadFromStorage();
myUser.name = "Jane Doe"
await saveToStorage(myUser);
});
I have a large json file with all my previous users. I need to prepare them to be imported. I keep getting this error : Error 4 failed to import: FirebaseAuthError: The password hash must be a valid byte buffer.
What is the proper way to store a hashed password as byte buffer in a json?
var jsonFile = require('./users.json');
var fs = require('fs')
let newArr = []
jsonFile.file.slice(0, 5).map( val => {
newArr.push({
uid: val.id,
email: val.email,
passwordHash: Buffer.from(val.password) // val.password is hashed
})
})
let data = JSON.stringify(newArr);
fs.writeFileSync('newArr.json', data);
In my main import file
var jsonFile = require('./newArr.json');
// I was testing it like that and everything is working fine.
const userImportRecords = [
{
uid: '555555555555',
email: 'user#example.com',
passwordHash: Buffer.from('$2a$10$P6TOqRVAXL2FLRzq9Ii6AeGqzV4mX8UNdpHvlLr.4DPxq2Xsd54KK')
}
];
admin.auth().importUsers(jsonFile, {
hash: {
algorithm: 'BCRYPT',
rounds: 10
}
})
Your first code snippet writes Buffer values to the file system. This doesn't work the way you expect. For instance, try running the following example:
const val = {uid: 'test', passwordHash: Buffer.from('test')};
fs.writeFileSync('newArr.json', JSON.stringify(val));
The resulting file will contain the following text:
{"uid":"test","passwordHash":{"type":"Buffer","data":[116,101,115,116]}}
When you require() this file, the passwordHash gets assigned to the object { type: 'Buffer', data: [ 116, 101, 115, 116 ] }. That's not the Buffer type expected by the importUsers() API.
I believe your newArr variable contains the right kind of array that can be passed into importUsers(). But writing it to the file system, and then reloading it changes the type of all Buffer fields.
I found a workaround to this problem. I'm parsing users.json directly inside the importUsers() file. Since I don't have to store the Buffer inside a json file again, the passwordHash stay a buffer.
This is the right way to do it
let newArr = []
jsonFile.file.slice(0, 5).map( val => {
newArr.push({
uid: val.id,
email: val.email,
passwordHash: Buffer.from(val.password)
})
})
admin.auth().importUsers(newArr, {
hash: {
algorithm: 'BCRYPT',
rounds: 10
}
})
how to append the nested object in FormData, my object is
{
name: 'test',
phone: '454353',
address: [
{
state: 'ewrwer',
city: 'asdasd'
}
]
}
I had append like this
const data = new FormData();
data.append("name", "test");
data.append("phone", "454353");
data.append("address['state']", "ewrwer");
data.append("address['city']", "asdasd");
but this is not working for me when I send this formData in request body the address is not working.
It should be:
data.append("address[0]['state']", "ewrwer");
data.append("address[0]['city']", "asdasd");
Because, it is inside array of index 0, then inside that you have addresses.
I'd like to send some custom object in a POST request but synchronously, i.e. I want the browser to refresh and load the new target page, and I do not want to make an ajax request.
In other words, I'd like to submit a form with some custom data object made out of the values of its fields. How would I do that?
function postData()
{
var person = { FirstName: "John", LastName: "Doe" };
// How do I send the person object as a part of the POST data
$("#myForm").submit();
}
You can create the form on the fly:
var myForm = $('<form>', { method: 'POST', target: 'YOUR_TARGET' } ); // create a new form
myForm.append($('<input>', { name: 'FirstName', value: 'John' }));
myForm.append($('<input>', { name: 'LastName', value: 'Doe' }));
myForm.hide().appendTo('body');
myForm.submit()
However, in case you just want to add custom data to an existing form, you can do this instead
var myForm = $('#myForm');
myForm.append($('<input>', { type: 'hidden', name: 'FirstName', value: 'John' }));
myForm.submit()