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 框架将字符串作为文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 jQuery 或其他 js 框架将字符串作为文件
 
				
         
 
            
        基础教程推荐
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
						 
						 
						 
						 
						 
				 
				 
				 
				