N
N
Nadim Zakirov2021-08-11 19:46:50
AJAX
Nadim Zakirov, 2021-08-11 19:46:50

How to correctly compose the request body with multipart / form-data?

I want to manually send a file, an example of a request body part:

Content-Disposition: form-data; name="myfile"; filename="pic.jpg"
Content-Type: image/jpeg
(пустая строка)
содержимое файла

Instead of the contents of the file, I tried to substitute the output from both reader.readAsText and reader.readAsBinaryString , but alas, in both cases I get a broken file on the server side. What is this mysterious content of the file about which the documentation does not say a word? In what encoding should I substitute the file, even if the binary string does not fit?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexandroppolus, 2021-08-11
@zkrvndm

https://learn.javascript.ru/formdata
or do you want it manually? Then the easiest option is through the blob constructor

const body = new Blob(['some text', file, 'some text 2', ...]);

This thing just takes and concatenates everything into one blob, which you just send to fetch. In this case, the lines are automatically encoded in utf8, and the files simply copy their bytes. Here strings are form text values, delimiters and other service crap, but files are files that don't even need to be read by a FileReader.

W
writer_2159, 2021-08-12
@writer_2159

Here's an option right out of the box

const formData = new FormData();
formData.append('file', document.querySelector('input[type=file]').files[0]);

fetch('http:google.com', {
        body:formData,
        'POST',
    });

on the PHP side it is accepted as $_FILES

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question