How to upload string as file with jQuery or other js framework(如何使用 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
并玩转有点格式,我写了这个Plain Ol' 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 框架将字符串作为文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!