如何使用jQuery或其他js框架上传字符串作为文件

Rom*_*mka 12 javascript ajax upload jquery extjs

使用javascript,我有一个字符串文件(带有ajax请求).

如何通过另一个ajax请求将其作为文件上传到服务器?

And*_*y E 16

您需要将Content-type请求标头设置为multipart/form-data并稍微使用该格式,在Plain Ol'JavaScript(tm)中写了这个,但您可以轻松地为库重写它:

编辑:现在喝咖啡,所以修改它为jQuery(这里没有库版本):

// 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) {
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 除了使用express/node进行两次调整之外,这是有效的:1)最后一个边界需要是'+' - '+ boundary +' - ';`而且ajax调用中的contentType需要是:`" multipart/form-data; boundary ="+ boundary" (4认同)

小智 16

以下是如何在不手动构建多部分请求主体的情况下执行此操作:

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
    }
});
Run Code Online (Sandbox Code Playgroud)