小编典典

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

ajax

使用javascript,我有一个字符串文件(使用ajax请求获取)。

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


阅读 315

收藏
2020-07-26

共1个答案

小编典典

您需要将Content-typerequest标头设置为,multipart/form- data并稍微调整一下格式,我用PlainOl’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) {
    }
});
2020-07-26