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 must 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);
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With