Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manually create multipart/form-data

We can use .formData() of Body mixin to return a FormData representation of data at Chromium (Chrome) 60+ and Firefox 39+

Relevant specifications:

  • 7.2 The Multipart Content-Type
  • Returning Values from Forms: multipart/form-data

Errata

  • Clarification of Body package data algorithm with bytes, FormData and multipart/form-data MIME type #392
  • Documenting de-facto handling of multipart/form-data form field file uploads #3040

Related

  • Multipart HTTP response
  • How to upload files in Web Workers when FormData is not defined

How to manually create multipart/form-data using JavaScript at client and at server to serve the multipart/form-data as a response?

like image 824
guest271314 Avatar asked Nov 02 '17 17:11

guest271314


People also ask

How do I create a multipart form data?

Multipart form data: The ENCTYPE attribute of <form> tag specifies the method of encoding for the form data. It is one of the two ways of encoding the HTML form. It is specifically used when file uploading is required in HTML form. It sends the form data to server in multiple parts because of large size of file.

How you can add data to FormData?

append() The append() method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.

How do you set content type as multipart form data?

For the most part, the main difference is the Content-Type of the different form fields or “Parameters”. The first form part should be “application/json” and the binary file type should be “application/pdf”.


1 Answers

You can create multipart/form-data manually with XMLHttpRequest like this example.

function multiPost(method, url, formHash){
    var boundary = "nVenJ7H4puv"
    var body = ""
    for(var key in formHash){
        body += "--" + boundary
             + "\r\nContent-Disposition: form-data; name=" + formHash[key].name
             + "\r\nContent-type: " + formHash[key].type
             + "\r\n\r\n" + formHash[key].value + "\r\n"
    }
    body += "--" + boundary + "--\r\n"

    var xml = new XMLHttpRequest();
    xml.open(method, url)
    xml.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary)
    xml.setRequestHeader("Content-Length", body.length)
    xml.send(body)
}
like image 110
sapics Avatar answered Oct 07 '22 06:10

sapics