How to create an AJAX request with JavaScript that contains both file data and messages

How to create an HTTP request that sends a single file and some mail data using JavaScript that can be received by the PHP server?

I found the following sentence, but it does not seem complete

xhr.open("POST", "upload.php");
var boundary = '---------------------------';
boundary += Math.floor(Math.random()*32768);
boundary += Math.floor(Math.random()*32768);
boundary += Math.floor(Math.random()*32768);
xhr.setRequestHeader("Content-Type", 'multipart/form-data; boundary=' + boundary);
var body = '';
body += 'Content-Type: multipart/form-data; boundary=' + boundary;
//body += '\r\nContent-length: '+body.length;
body += '\r\n\r\n--' + boundary + '\r\n' + 'Content-Disposition: form-data; name="';
body += 'myfile"; filename="'+file.fileName+'" \r\n';
body += "Content-Type: "+file.type;
body += '\r\n\r\n';
body += file.getAsBinary();
body += '\r\n'
body += '--' + boundary + '\r\n' + 'Content-Disposition: form-data; name="submitBtn"\r\n\r\nUpload\r\n';
body += '--' + boundary + '--';
xhr.setRequestHeader('Content-length', body.length);

To get this working, I need to have a variable 'file' that contains a field of type input type, but where to add additional data for publication? I want to send a description text. suppose I also need to use xhr.send to send a request ...

+3
source share
3 answers

POST Content-Disposition. :

Content-Type: multipart/form-data; boundary=AaB03x

--AaB03x
Content-Disposition: form-data; name="submit-name"

Larry
--AaB03x
Content-Disposition: form-data; name="files"; filename="file1.txt"
Content-Type: text/plain

... contents of file1.txt ...
--AaB03x--

: = "submit-name" Larry. Content-Dispositions, POST.

, , js-, ​​ jQuery. , .

+2

jquery? XHR.

-1

AFAIK Unable to send files using XmlHttpRequest.

-2
source

Source: https://habr.com/ru/post/1764281/


All Articles