Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

javascript - Converting base64 image to multipart/form-data and sending with jQuery

I have a base64 encoded jpg in javascript which I would like to post to a server which is expecting multipart/form-data.

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

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

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.

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) 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 = '
',

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;

Then just send it of:

xhr.setRequestHeader("Content-type", "multipart/form-data; boundary="+boundary);
xhr.setRequestHeader("Content-length", content.length);
xhr.setRequestHeader("Connection", "close");
// execute
xhr.send(content);

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.

Hope that helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...