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

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

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

您需要将Content-type请求标头设置为multipart/form-data并稍微使用该格式, 我在Plain Ol’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) { } }); 

以下是如何在不手动构建多部分请求主体的情况下执行此操作:

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