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 框架将字符串作为文件


基础教程推荐
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01