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

3

13

Using javascript, I have a file in string (got with ajax request).

How to upload it as file to server by another ajax request ?

Brick answered 10/6, 2010 at 7:49 Comment(2)
Please clarify: do you have file path as a string or you have file content as string and you would like to have it uploaded as a file?Lineage
@Marko: It reads like he has the file contents in a string, which he got from an ajax request.Pyrogallate
P
17

You need to set the Content-type request header to multipart/form-data and play around with the format a little, I wrote this in Plain Ol' JavaScript (tm) but you could easily rework it for a library:

EDIT: had my coffee now, so modified it for jQuery (no-library version here):

// Define a boundary, I stole this from IE but you can use any string AFAIK
var boundary = "---------------------------7da24f2e50046";
var body = '--' + boundary + '\r\n'
         // Parameter name is "file" and local filename is "temp.txt"
         + 'Content-Disposition: form-data; name="file";'
         + 'filename="temp.txt"\r\n'
         // Add the file's mime-type
         + 'Content-type: plain/text\r\n\r\n'
         // Add your data:
         + data + '\r\n'
         + '--'+ boundary + '--';

$.ajax({
    contentType: "multipart/form-data; boundary="+boundary,
    data: body,
    type: "POST",
    url: "http://asite.com/apage.php",
    success: function (data, status) {
    }
});
Pyrogallate answered 10/6, 2010 at 7:58 Comment(4)
Mmm, nice! Didn't know that was possible in an Ajax request.Finnic
@Pekka: Sure is. Handy if you don't have control over the server you're uploading to and it HAS to accept a text file posted with multipart/form-data.Pyrogallate
This worked, except for two adjustments to work with express/node: 1) the last boundary needs to be + '--'+boundary+ '--'; and also the contentType in the ajax call needs to be: "multipart/form-data; boundary="+boundaryTerresaterrestrial
@Terresaterrestrial this is also needed for Rails. Thanks, you just saved me a few hours of debuggingWinebaum
I
21

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
    }
});
Inaccessible answered 17/12, 2015 at 17:1 Comment(4)
seems nice... can i transcode Base64 to a File Object? If no i can use the base64 and decode it on the server. but im just curiousSaffron
Is FormData object cross browser compatible?Asci
I'm using Dropzone, but this answer works to convert a string to a file for upload("new File([new Blob([s])], filename)").Kataway
why is contentType false?Ragouzis
P
17

You need to set the Content-type request header to multipart/form-data and play around with the format a little, I wrote this in Plain Ol' JavaScript (tm) but you could easily rework it for a library:

EDIT: had my coffee now, so modified it for jQuery (no-library version here):

// Define a boundary, I stole this from IE but you can use any string AFAIK
var boundary = "---------------------------7da24f2e50046";
var body = '--' + boundary + '\r\n'
         // Parameter name is "file" and local filename is "temp.txt"
         + 'Content-Disposition: form-data; name="file";'
         + 'filename="temp.txt"\r\n'
         // Add the file's mime-type
         + 'Content-type: plain/text\r\n\r\n'
         // Add your data:
         + data + '\r\n'
         + '--'+ boundary + '--';

$.ajax({
    contentType: "multipart/form-data; boundary="+boundary,
    data: body,
    type: "POST",
    url: "http://asite.com/apage.php",
    success: function (data, status) {
    }
});
Pyrogallate answered 10/6, 2010 at 7:58 Comment(4)
Mmm, nice! Didn't know that was possible in an Ajax request.Finnic
@Pekka: Sure is. Handy if you don't have control over the server you're uploading to and it HAS to accept a text file posted with multipart/form-data.Pyrogallate
This worked, except for two adjustments to work with express/node: 1) the last boundary needs to be + '--'+boundary+ '--'; and also the contentType in the ajax call needs to be: "multipart/form-data; boundary="+boundaryTerresaterrestrial
@Terresaterrestrial this is also needed for Rails. Thanks, you just saved me a few hours of debuggingWinebaum
S
2

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))
Spokeshave answered 8/4, 2021 at 10:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.