I am working on this JSFiddle. I have converted the form fields to formData so that it could handle file contents as well. When I upload any file, it always shows empty. Could anyone please tell me why?
Btw, I stole the following two lines that I used in my JSFiddle from this Stackoverflow post
var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
Looking at your fiddle, it seems you’re trying to serialize the form to JSON, but files can’t be represented as JSON. If you want to upload files, the request needs to be sent as the type multipart/form-data.
Thanks. Actually, I don’t want to upload but send the file related information to my Java webservice which is accepting a JSON object and that’s why I was trying to convert it into JSON but it looks like that’s not possible.
Do you think I could do the following at the same time :
convert file related information into JSON type of format and then send it to my Java web service separately
and at the same time my other form related entries will also be sent in JSON format to the Java webservice
Sure, that’s certainly possible. Two questions for you, though:
What sort of information are you wanted to send about the file?
Does the information about the file need to be sent as a separate request (i.e. is it going to a separate URL), or can it be combined with the form data?
I would like to send the content of the file, name of the file and mime type.
It can be combined with the formdata. And if it’s possible to convert it into the format just like JSON object, that’s great because I have designed my java webservice to accept it in the form of name and value pairs. I mean something like the following for file #1 :
Ah, no, as far as I know it’s not possible to open files using JavaScript in the browser.
I think your best bet in this situation would be to send the files and the form data as a multipart form, and extract the contents (and whatever metadata you need) server-side.