如何使用 jQuery 或其他 js 框架将字符串上传为文件 [英] How to upload string as file with jQuery or other js framework

查看:11
本文介绍了如何使用 jQuery 或其他 js 框架将字符串上传为文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 javascript,我有一个字符串文件(通过 ajax 请求获得).

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

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

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

推荐答案

您需要将 Content-type 请求头设置为 multipart/form-data 并玩转稍微使用格式,我写了这个普通的 JavaScript (tm),但您可以轻松地将其改写为库:

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:

现在喝了咖啡,所以针对 jQuery 修改了它(无库版本 此处):

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 + '
'
         // Parameter name is "file" and local filename is "temp.txt"
         + 'Content-Disposition: form-data; name="file";'
         + 'filename="temp.txt"
'
         // Add the file's mime-type
         + 'Content-type: plain/text

'
         // Add your data:
         + data + '
'
         + '--'+ boundary + '--';

$.ajax({
    contentType: "multipart/form-data; boundary="+boundary,
    data: body,
    type: "POST",
    url: "http://asite.com/apage.php",
    success: function (data, status) {
    }
});

这篇关于如何使用 jQuery 或其他 js 框架将字符串上传为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆