Comments (17)
Hey,
The thing is you can send only strings over the wire, so complex data types, like object should be encoded somehow and since there are many way to encode objects, FormData leaves it to developer to choose proper encoding mechanism that supported on the other end. For example it could be a JSON
string or a form-urlencoded
string.
Something like:
var details = JSON.stringify({age: 12});
form.append('details', details);
Let me know if you have more questions.
from form-data.
I was trying to post a complex data structure without pickling it into json to set up a simple data flow from React to Rails, and this thread was the most helpful piece of information. Just in case someone is looking for an example:
data to be posted:
{
library: "favorite",
movie: {
name: "James Bond Skyfall",
year: "2012",
screenshots: [file1, file2],
},
}
implementation with FormData
:
const formData = new FormData()
formData.append("library", "favorite")
formData.append("movie[name]", "James Bond Skyfall")
formData.append("movie[year]", "2012")
formData.append("movie[screenshots][]", file1)
formData.append("movie[screenshots][]", file2)
from form-data.
You'd need to handle decoding one way or another and because implementations differ from server to server, you need to find combination that would work for your setup.
One of the ways is to stay away from nested structure, something like:
var form = new FormData();
form.append('name', 'Name');
form.append('age', '12');
or
var form = new FormData();
form.append('name', 'Name');
form.append('details_age', '12');
or PHP-style (not sure if Hapi would support it out of the box):
var form = new FormData();
form.append('name', 'Name');
form.append('details[age]', '12');
Another solution will be to encode all your data as JSON and send it to the server with proper headers,
there should be examples in Hapi documentation.
from form-data.
it maybe common case for some apps, but some other apps work with url-encoded data, and even with url-encoding there are multiply ways, like standard HTTP way and PHP array-friendly way.
And if all you need is JSON.stringify
, there should be no problem in doing it in "user"-land (i.e. form.append('data', JSON.stringify(myData))
, right?
Throwing errors in general meant for developer errors, to notify developer of the unacceptable behavior. And for developers it's much easier to find out about the problem this way, then somewhere deeper in stack because some library took freedom to assume things for the developer, especially for dynamic languages like JS, where you can accidentally pass object instead of a string.
from form-data.
Hello,
thanks for the response. My use case is that I am using this module just in my tests to simulate the form post to the hapijs server.
I've already tried JSON.stringify but unfortunately, the field was arriving as a string instead of an object. I don't want to add into my production code logic to parse some of the fields from string to json just because of tests:(
from form-data.
Thanks php style helped for hapi, I thought that I' ve already tried this, but obviously I had some bug there before :)
from form-data.
How about if append
receives an object then it assumes it should be encoded with JSON.stringify
and it sets Content-Type
to application/json
? This seems like a common use case to me.
It wouldn't be worse than the current behavior of TypeError: Object #<Object> has no method 'on'
.
from form-data.
Excellent points, I agree.
from form-data.
Is there any npm module for transforming an object to PHP style array? recursively
from form-data.
Found one: https://github.com/therealparmesh/object-to-formdata/
from form-data.
i can not append list of objects to my form data i got empty list on the action
$.each(selectLists, function (key, selectList) { var SingelValue = { ItemId: singleList.id, inputValue: singleList.value } SingelValue = JSON.stringify(SingelValue); fdata.append("SingelValues[]", SingelValue) }
from form-data.
I use Swagger2.0, mongoDB as database and I am trying to go with the stringify() during sending and decode in the Flask server side.
Surprisingly, even though I defined the schema in the swagger UI for such field as string. During get fields, it will still directly get the json array instead of string format... This satisfies my need, but it doesn't make sense. Could someone give me an explanation on this?
from form-data.
can I append the Object as it is, without Stringify it?
from form-data.
@abned08 no, you may stringify it or use @alexsmartens's solution. FormData.append() only accepts USVString
and Blob
.
from form-data.
Thanks a lot to @alexsmartens for example. I was 3, 4 days without can send objects in FormData post and his example really help me to success.
e.g (C#):
public JsonResult AddTicketUser(TicketViewModel ticketVM) //ticketVM has a Ticket object inside.
I believe that @alexindigo is elegant solution but I not sure how implements in my case. ( Use enctype: 'multipart/form-data' and contentType: false).
greetings :)
from form-data.
Following @alexsmartens example here's a handy js function to append an object to FormData
function FormData_append_object(fd, obj, key) {
var i, k;
for(i in obj) {
k = key ? key + '[' + i + ']' : i;
if(typeof obj[i] == 'object')
FormData_append_object(fd, obj[i], k);
else
fd.append(k, obj[i]);
}
}
And here's is how you would call it:
var myObject = { a: 'one', b: { b1: 'two', b2: { b21: 'three', b22: 'four' } }, d: 'five' };
fd = new FormData();
FormData_append_object(fd, myObject);
It works great calling ajax from js to PHP.
from form-data.
Hey,
The thing is you can send only strings over the wire, so complex data types, like object should be encoded somehow and since there are many way to encode objects, FormData leaves it to developer to choose proper encoding mechanism that supported on the other end. For example it could be a
JSON
string or aform-urlencoded
string.Something like:
var details = JSON.stringify({age: 12}); form.append('details', details);
Let me know if you have more questions.
In case this is useful for somebody else, in the case you are using Express
Multer you can use file.buffer.toString()
from form-data.
Related Issues (20)
- getHeaders should add content length if known HOT 1
- Passing Uint8Array or Buffer leads to "source.on is not a function" error under Node 18 HOT 1
- Need Help Browser support HOT 3
- Final nail in the coffin HOT 1
- Is there a place to report security issues? HOT 2
- From Data HOT 1
- Is this Library Dead? HOT 2
- "form-data" is vulnerable to request tampering via a crafted filename HOT 1
- FormData is undefind
- FormData is undefind
- FormData class is confused with native FormData class in Chrome HOT 1
- Doesn't work well in node version 18 HOT 3
- any option to Read all the key and value from formdata HOT 1
- How to send an array of pdf files using form-data HOT 5
- How do I get upload progress when I submit??? HOT 1
- Mark package with sideEffects: false
- how to upload multiple files with fields at once with formdata
- Is it possible to cancel a fileupload?
- 【formData】“Error: Unexpected end of form” after multiple post file formdata, and then hang up after multiple error happening HOT 2
- Move away from `util.isArray`
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from form-data.