views:

80

answers:

1

using javascript.
I have a file in string (getted with ajax request). How to upload it as file to server by another ajax request ?

+5  A: 

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",
    data: body,
    type: "POST",
    url: "http://asite.com/apage.php",
    success: function (data, status) {
    }
});
Andy E
Mmm, nice! Didn't know that was possible in an Ajax request.
Pekka
@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.
Andy E