2010-06-10 59 views
9

使用JavaScript,我有一个字符串文件(与Ajax请求得到)。如何上传字符串作为文件与jQuery或其他js框架

如何通过另一个Ajax请求上传的文件服务器?

+1

请澄清一下:你是否有文件路径作为字符串,或者你有文件内容作为字符串,你想它作为文件上传? – 2010-06-10 07:54:20

+0

@Marko:它看起来像他有一个字符串中的文件内容,他从ajax请求中获得。 – 2010-06-10 08:01:24

回答

13

您需要将Content-type请求头设置为multipart/form-data和玩的纯醇”的JavaScript(TM)格式的一点,I wrote this但你可以很容易地返工为图书馆:

编辑:有我咖啡了,所以修改了它的jQuery(无库版本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) { 
    } 
}); 
+1

嗯,真好!不知道这在Ajax请求中是可能的。 – 2010-06-10 08:00:39

+0

@Pekka:好的。如果您无法控制要上传的服务器,并且必须接受使用多部分/表单数据发布的文本文件,方便使用。 – 2010-06-10 08:16:27

+4

这有效,除了使用express/node进行两次调整外:1)最后一个边界需要是'+' - '+ boundary +' - ';'并且ajax调用中的contentType必须是:'' “multipart/form-data; boundary =”+ boundary' – chovy 2013-01-24 23:35:19

7

这里是如何做到这一点,而无需手动建立多部分请求主体:

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 
    } 
}); 
+0

似乎很好...我可以将Base64转码为文件对​​象吗?如果没有,我可以使用base64并在服务器上解码它。但我只是好奇 – redestructa 2016-09-06 08:53:02

+0

FormData对象跨浏览器兼容? – 2016-10-05 04:41:14

相关问题