Using javascript, I have a file in string (got with ajax request).
How to upload it as file to server by another ajax request ?
Here's how to do it without manually building the multi-part request body:
var s = 'some string data';
var filename = 'foobar.txt';
var formData = new FormData();
formData.append('file', new File([new Blob([s])], filename));
formData.append('another-form-field', 'some value');
$.ajax({
url: '/upload',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function () {
console.log('ok');
},
error: function () {
console.log('err'); // replace with proper error handling
}
});
Solution using new FormData() without ajax
str = "Hello!\nI'm text string";
var strblob = new Blob([str], {type: 'text/plain'});
var formdata = new FormData();
formdata.append("file", strblob, "file.txt");
formdata.append("field-1", "field-1-data");
var requestOptions = {
method: 'POST',
body: formdata,
redirect: 'follow'
};
fetch("http://{url}", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With