lat*_*lip 8 javascript api jquery base64
我在javascript中有一个base64编码的jpg,我想发布到期望multipart/form-data的服务器.
具体来说,对于关键跟踪器API,它有一个示例curl调用,如下所示:
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
Run Code Online (Sandbox Code Playgroud)
我有基本的XML调用他们的API工作正常,使用.ajax像这样:
$.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'); }
});
Run Code Online (Sandbox Code Playgroud)
但我很难理解如何使用我的base64编码的jpg并发送它,好像我已经在表单中上传了一个文件.
有任何想法吗?
非常坦率的。我像你一样用 JQuery 尝试过,但无法完成。因此,我继续构建自己的 XHR 实现,它将向服务器发送自定义的多部分正文。
1) 初始化您的 XHR 2) 一起构建多部分主体 3) 发送
var xhr = new XMLHttpRequest();
...
xhr.open("POST", url, true);
var boundary = '------multipartformboundary' + (new Date).getTime(),
dashdash = '--',
crlf = '\r\n',
Run Code Online (Sandbox Code Playgroud)
这就是奇迹发生的地方。您构建自己的传输“主体”,并将图像数据作为带有名称的普通变量放入主体中:
content = dashdash+boundary+crlf+'Content-Disposition: form-data; name="NAMEOFVARIABLEINPHP";"'+crlf+crlf+VARIABLEWITHBASE64IMAGE+crlf+dashdash+boundary+dashdash+crlf;
Run Code Online (Sandbox Code Playgroud)
然后只需发送:
xhr.setRequestHeader("Content-type", "multipart/form-data; boundary="+boundary);
xhr.setRequestHeader("Content-length", content.length);
xhr.setRequestHeader("Connection", "close");
// execute
xhr.send(content);
Run Code Online (Sandbox Code Playgroud)
如果您使用 PHP,则 $_POST 中有一个新变量,其中包含 base64 编码的字符串。这将防止浏览器将字符串分解为 72 个字符/行并去除 + 和其他特殊字符。
希望有帮助。