Send multipart / form-data including file and json form extra data with jQuery AJAX data

I have an HTTP API that waits for a message with multiple data / data form with this structure:

--boundary Content-Disposition: form-data; name=""Meta"" Content-Type: application/json {""Title"":""title"",""Description"":""description"",""Number"":3} --boundary Content-Disposition: form-data; name=""file""; filename=""fileName"" Content-Type: text/plain Content-Transfer-Encoding: 7BIT some text content --boundary 

I am trying to make a whit FormData message structure as follows:

 var data = new FormData(); data.append("Meta", "Content-Type: application/json\r\n\r\n" + [JSON.stringify({ Title: "title", Description: "description", Number: 3})] + "\r\n"); data.append('File', document.getElementById("file").files[0]); $.ajax({ url: myservice, data: data, cache: false, processData: false, contentType: false, type: 'POST', success: function (data, status, req) { alert("OK"+req); }, error: function (req, status, error) { alert("ERROR"+req); } }); 

However, I cannot add a content type to a section without a file.

With this approach, I create a message with the remaining line of interruption between the Content-Disposition and the Content-Type.

 -----------------------------10743159127866 Content-Disposition: form-data; name="Meta" Content-Type: application/json {"Title":"title","Description":"description","Number":3} -----------------------------10743159127866 Content-Disposition: form-data; name="File"; filename="b839f0cc60ac4fb68f826b20cd02873b.pdf" ... 
+5
source share
1 answer
 <script type="text/javascript"> $(document).ready(function() { $("#submit").click(function() { var fileInput = document.getElementById('image'); var file = fileInput.files[0]; var formData = new FormData(); formData.append('file', file); $.ajax({ url: "url.php", type: "POST", data: "file="+file, cache: false, success: function(res) { alert(res); }, error: function(err){ alert(err); } }); }); 

});

0
source

All Articles