how to specify binary data in jquery post function
I have screenshot as binary string. I'd like to post some data to server using $.post() function.
My code:
var filename = "screenshot.jpg":
var filedataUrl = "";// string like 'data:image/jpeg;base64,/9j/4A .....'
$.post(serverUrl, {
title: title
name: name
/*here mu开发者_StackOverflow中文版st be my file */
}, function(response) {
alert('ok');
});
How can I specify parameter as attached file?
Technically base64 is a text representation of binary data - if you are fine with this above answers are correct. If you want to send real binary data you have to use FormData.
If I'm reading your question correctly you are saving html "screenshot" to canvas element. If so instead of reading toDataURL
you should use toBlob. This will give you binary data that we can send using FormData
var form = new FormData();
form.append('image', blob, 'image.jpg');
Above can be send using regular XMLHttpRequest
:
var request = new XMLHttpRequest();
request.open('POST', 'http://foo.com/submitform.php');
request.send(form);
Working example -> codepen
If you will look into chrome inspector you will see that correct multipart request is created:
------WebKitFormBoundaryGWsPW93HnMPQFcXB
Content-Disposition: form-data; name="image"; filename="image.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryGWsPW93HnMPQFcXB--
You can also send above form with jQuery:
$.ajax({
url: 'http://foo.com/submitform.php',
type: 'POST',
data: form,
processData: false,
contentType: false
});
Update
Just saw your notice about handling file upload on server side in PHP. Uploaded file is available in $_FILES array:
<?php
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['image']['name']);
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
echo "File was successfully uploaded.\n";
} else {
echo "Error";
}
echo 'File info:';
print_r($_FILES);
?>
Use data
Example:
$.post({
url: serverUrl,
data: {
'fileasstring': filedataUrl
},
success: function(response) {
alert('ok');
}
});
See: http://api.jquery.com/jQuery.post/
You will need to do a few things.
First you will need to breakup the filedataUrl. You want only the base64 data, not the rest. Then use the methods in Base64 encoding and decoding in client-side Javascript to base64 decode the string into variable holding binary data.
Then include that variable in your post request.
I dont think you can upload the image using a filename. You may need to create a form with file input element where the user can choose a file (not through javascript).
Then submit the form using AJAX.
base64
encoded image is also a normal string. You can pass it as a data
to the jQuery POST.
It will be like the following.
var filename = "screenshot.jpg":
var filedataUrl = "";// string like 'data:image/jpeg;base64,/9j/4A .....'
$.post(serverUrl, {
title: title,
name: name,
image: filedataUrl,
})
.done(function(res){
alert('ok')
})
精彩评论