将base64图像转换为多部分/表单数据并使用jQuery发送 [英] Converting base64 image to multipart/form-data and sending with jQuery
问题描述
我在javascript中有一个base64编码的jpg,我想将其发布到需要multipart/form-data的服务器上.
I have a base64 encoded jpg in javascript which I would like to post to a server which is expecting multipart/form-data.
具体来说,对于关键跟踪器API,该示例具有一个curl调用示例,如下所示:
Specifically, to the pivotal tracker API, which has an example curl call like so:
curl -H "X-TrackerToken: TOKEN" -X POST -F Filedata=@/path/to/file \
http://www.pivotaltracker.com/services/v3/projects/PROJECT_ID/stories/STORY_ID/attachments
我只有基本XML对其API的调用才能正常工作,使用.ajax就像这样:
I have basic XML only calls to their API working fine, using .ajax like so:
$.ajax({
url: 'http://www.pivotaltracker.com/services/v3/projects/158325/stories',
type: 'POST',
contentType: 'application/xml',
dataType: 'xml',
beforeSend: function(xhr) {
xhr.setRequestHeader("X-TrackerToken", "<KEY>")
},
data: '<story><story_type>feature</story_type><name>Fire torpedoes</name></story>',
success: function() { alert('PUT completed'); }
});
但是我对如何获取以base64编码的jpg并以好像已以表格形式上传文件的方式发送它感到困惑.
but I am stumped on how to take my base64 encoded jpg and send it as if I had uploaded a file in a form.
有什么想法吗?
推荐答案
完全简单.我像您一样使用JQuery尝试过,但无法完成.因此,我继续构建自己的XHR实现,该实现将自定义的多部分主体发送到服务器.
Fairly straight forward. I tried it with JQuery as you did, but couldn't accomplish it. So I went ahead and build my own XHR implementation that will send a custom multipart body to the server.
1)初始化您的XHR 2)一起建立多部分的身体 3)发送
1) Initialize your XHR 2) Build the multipart body together 3) Send it
var xhr = new XMLHttpRequest();
...
xhr.open("POST", url, true);
var boundary = '------multipartformboundary' + (new Date).getTime(),
dashdash = '--',
crlf = '\r\n',
这是魔术发生的地方.您为传输建立自己的主体",并将图像 data 作为具有 name 的普通变量放入主体:
This is were the magic happens. You build your own "body" for the transmission and put the image data as a normal variable with name into the body:
content = dashdash+boundary+crlf+'Content-Disposition: form-data; name="NAMEOFVARIABLEINPHP";"'+crlf+crlf+VARIABLEWITHBASE64IMAGE+crlf+dashdash+boundary+dashdash+crlf;
然后将其发送给:
xhr.setRequestHeader("Content-type", "multipart/form-data; boundary="+boundary);
xhr.setRequestHeader("Content-length", content.length);
xhr.setRequestHeader("Connection", "close");
// execute
xhr.send(content);
如果使用PHP,则$ _POST中将包含一个新变量,其中包含base64编码的字符串.这样可以防止浏览器将字符串分成72个字符/行,并去除+和其他特殊字符.
If you use PHP, you have a new variable in your $_POST containing the base64 encoded string. This will prevent that the browser is breaking the string into 72 chars/line and stripping out the +'s and other special chars.
希望有帮助.
这篇关于将base64图像转换为多部分/表单数据并使用jQuery发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!