如何上传字符串的文件与jQuery或其它JS框架 [英] How to upload string as file with jQuery or other js framework
问题描述
使用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 ?
推荐答案
您需要设置内容类型
请求头的multipart /表单-data code>,并与格式玩了一下,<一个href="http://stackoverflow.com/questions/2198470/javascript-uploading-a-file-without-a-file/2198524#2198524">I写这篇在纯醇'的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(无库版本<一href="http://stackoverflow.com/questions/2198470/javascript-uploading-a-file-without-a-file/2198524#2198524">here):
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; boundary="+boundary,
data: body,
type: "POST",
url: "http://asite.com/apage.php",
success: function (data, status) {
}
});
这篇关于如何上传字符串的文件与jQuery或其它JS框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!