How to upload string as file with jQuery or other js framework

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
    }
});

Leave a Comment