I'm trying to send created photo in android via ajax via remote API. I'm using Camera Picture Background plugin.
Photo is created properly, I'm getting it via ajax GET request and encode it to base64 format. In debugging tool I can see image itself through GET request log.
Next I parse it base64 to Blob and try to attach it to FormData:
var fd = new FormData();
fd.append('photo', blobObj);
$.ajax({
type: 'POST',
url: 'myUrl',
data: fd,
processData: false,
contentType: false
}).done(function(resp){
console.log(resp);
}). [...]
But when I send the FormData I see in debugger that FormData in request equals to: {photo: null}.
Btw. if I try to console.log my blobObj earlier, I see it is a blob, with its size, type properties and slice method - why it becomes a null after appending to FormData?
EDIT:
console.log(blobObj); gives:
Blob {type: "image/jpeg", size: 50778, slice: function}
EDIT2 - STEP BY STEP CODE:
I have url to local image, let's assume it is stored in imagePath variable.
First, I get this file and parse it to base64:
function base64Encode(){
var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var out = "", i = 0, len = str.length, c1, c2, c3;
while (i < len) {
c1 = str.charCodeAt(i++) & 0xff;
if (i == len) {
out += CHARS.charAt(c1 >> 2);
out += CHARS.charAt((c1 & 0x3) << 4);
out += "==";
break;
}
c2 = str.charCodeAt(i++);
if (i == len) {
out += CHARS.charAt(c1 >> 2);
RS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
out += CHARS.charAt((c2 & 0xF) << 2);
out += "=";
break;
}
c3 = str.charCodeAt(i++);
out += CHARS.charAt(c1 >> 2);
out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
out += CHARS.charAt(c3 & 0x3F);
}
return out;
}
function getFile(fileData){
var dfd = new $.Deferred();
$.ajax({
type: 'GET',
url: fileData,
mimeType: "image/jpeg; charset=x-user-defined"
}).done(function(resp){
var file = base64Encode(resp);
dfd.resolve(file);
}).fail(function(err){
console.warn('err', err);
dfd.resolve();
});
return dfd.promise();
};
$.when(getFile(imagePath)).then(function(resp){
var fd = new FormData();
resp = 'data:image/jpeg;base64,' + resp;
var imgBlob = new Blob([resp], {type : 'image/jpeg'});
fd.append('photo', img, 'my_image.jpg');
$.ajax({
type: 'POST',
url: 'myUrlToUploadFiles',
data: fd,
processData: false,
contentType: false
}).done(function(resp){
console.log(resp);
}). [...]
});
I've not done this recently, but this works with me. I hope it also works with you:
function getBase64ImageByURL(url) {
var dfd = new $.Deferred();
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
dfd.resolve(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.send();
return dfd.promise();
}
function base64ToBlob(base64Image,toMimeType) {
var byteCharacters = atob(base64Image.replace('data:'+toMimeType+';base64,',''));
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], {
type: toMimeType
});
return blob;
}
var imageUrl = "https://upload.wikimedia.org/wikipedia/commons/4/49/Koala_climbing_tree.jpg";
getBase64ImageByURL(imageUrl).then(function(base64Image){
var blob = base64ToBlob(base64Image,'image/jpeg');
var fd = new FormData();
fd.append('file', blob, 'my_image.jpg');
$.ajax({
url: 'http://your_host/uploads/testupload.php',
data: fd,
type: 'POST',
contentType: false,
processData: false,
success:function(res){
console.log(res);
},
error:function(err){
console.log(err);
}
})
});
On server-side(testupload.php):
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
$result = move_uploaded_file($_FILES['file']['tmp_name'], $_SERVER["DOCUMENT_ROOT"].$_SERVER["BASE"].'/uploads/'.'my_image.jpg');
var_dump("image uploaded: ".$result);
}
?>
It might be necessary to modify some read/write-permissions on a directory before move_uploaded_file succeeds in moving the uploaded image to this directory.
The function getBase64ImageByURL could already return a blob-object but by returning a base64-image you can show an user this image in a html-image-tag before uploading it for instance.
If there is no need to show an user that image, then you can also shorten all steps:
function getBlobImageByURL(url) {
var dfd = new $.Deferred();
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
dfd.resolve(xhr.response);
};
xhr.open('GET', url);
xhr.send();
return dfd.promise();
}
getBlobImageByURL(imageUrl).then(function(imageBlob){
var fd = new FormData();
fd.append('file', imageBlob, 'my_image.jpg');
console.log(fd.get('file'));// File-object
$.ajax({
url: 'http://your_host/uploads/testupload.php',
data: fd,
type: 'POST',
contentType: false,
processData: false,
success:function(res){
console.log(res);
},
error:function(err){
console.log(err);
}
})
});
references to both modified functions base64ToBlob and getBase64ImageByURL
Related
I am getting this error that Chrome failed to load the PDF document. I can see the content of the data is the console window so I have the data being returned I just not sure why it will not display? If I File.WriteAllBytes to disk it will open fine so it maybe something with the creating the new Blob
Failed to load PDF document.
ts code
printItems(versionKeys: string[]): JQueryPromise<any> {
console.log('printItems');
$.ajax({
type: "post",
contentType: "application/json",
data: JSON.stringify(versionKeys),
url: this.apiUrls.PrintTemplates,
success: function (data, status, xhr) {
console.log('printItems');
console.log(data);
let blob = new Blob([data.Content], { type: data.ContentType });
var url = URL.createObjectURL(blob);
console.log(url);
window.open(url);
console.log('success');
}
});
return;
}
Error
I converted the base64 string to a bytes
var binary_string = window.atob(data.Content)
var len = data.Content.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
let blob = new Blob([bytes.buffer], { type: data.ContentType })
var url = URL.createObjectURL(blob);
window.open(url);
I am just trying to upload image file in base64 format by storing it in a js object. But the problem here is the object property 'baseData' doesn't fill with the DataURL of the image. If the way I mentioned below is possible, please suggest the solution to fill the 'baseData' property.
What I am doing is storing the 'type' (image or video, not extensions) and DataURL of the file in the object(fileDataObject) and pushing the object to an array(blobData), and returning the same at the end of the function.
Thanks in advance
var filesAccept = filesValidator($("#file-upload")[0].files);
if(filesAccept !== false){
var fd = new FormData();
fd.append("files", filesAccept)
$.ajax({
type: "POST",
url: "receiver.php",
data: fd,
processData: false,
contentType: false,
dataType: "text",
success: function (result) {
console.log(result);
},
});
}
function filesValidator(f) {
if (f.length === 0) {
$("#error-info").text("Please select some images or videos.");
return false;
} else if(f.length !== 0) {
var blobData = [];
var fileType;
$("#error-info").text("");
var n = 10;
if (f.length < 10) {// checking if files count less than 10
n = f.length;
}
for (let i = 0; i < n; i++) {
var reader = new FileReader();
fileType = f[i].type.split("/");
if(fileType[1] === "gif"){
return false;
} else if (fileType[0] === "image") {// if file is images
reader.onload = function(e) {
var src = e.target.result.split(",")[1];
console.log(src);
var fileDataObject = {
baseData : src,
type : "image"
};
blobData.push(JSON.stringify(fileDataObject));
}
reader.readAsDataURL(f[i]);
} else if(fileType[0] === "video") { //if file is video
reader.onload = function(e) {
var src = e.target.result.split(",")[1];
var fileDataObject = {
baseData : src,
type : "video"
};
blobData.push(JSON.stringify(fileDataObject));
}
reader.readAsDataURL(f[i]);
}
console.log(blobData);
}
return blobData;
}
}
I'm trying to record a video (already working) using HTML5 video tag, "getUserMedia" to access the device camera and MediaRecorder API to capture the frames and Angular1 to handle the file uploading. Now I'm having trouble uploading the Blob to my PHP server which is running on Laravel, I currently have 2 ways to upload the video, first is by "ng-click" this works fine but when I programmatically upload the Blob using the same function which "ng-click" run it seems to break the mimeType of my Blob here's how my code looks.
$scope.uploader = function() {
let fData = new FormData();
let blob = new Blob($scope.chunk, { type: 'video/webm' });
fData.append('vid', blob)
$http.post(url, fData, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined},
}, success, error)
})
$timeout(function() {
$scope.uploader();
}, 10000)
This issue here is when the "$scope.uploader()" is called using "ng-click" it works fine but when calling the "uploader" method using the "$timeout" it seems to change the mimeType to "application/octet-stream" which causes the issue.
Hello Try this code,
function base64ToBlob(base64Data, contentType) {
contentType = contentType || '';
var sliceSize = 1024;
var byteCharacters = atob(base64Data);
var bytesLength = byteCharacters.length;
var slicesCount = Math.ceil(bytesLength / sliceSize);
var byteArrays = new Array(slicesCount);
for (var sliceIndex = 0;sliceIndex <slicesCount;++sliceIndex) {
var begin = sliceIndex * sliceSize;
var end = Math.min(begin + sliceSize, bytesLength);
var bytes = new Array(end - begin);
for (var offset = begin, i = 0;offset <end;++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, {
type: contentType});
}
Define scope
$scope.onFile = function(blob) {
Cropper.encode((file = blob)).then(function(dataUrl) {
$scope.dataUrl = dataUrl;
$scope.odataUrl = dataUrl;
$timeout(showCropper); // wait for $digest to set image's src
});
};
Submit method
$scope.uploadImage = function () {
if ($scope.myCroppedImage === '')
{
}
$scope.msgtype = "";
$scope.msgtxt = "";
var fd = new FormData();
var imgBlob = dataURItoBlob($scope.myCroppedImage);
fd.append('clogo', imgBlob);
fd.append('actionfile', 'editimage');
$http.post(
'../user/user_EditCompany.php',
fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
}
)
.success(function (response) {
// console.log(response);
if (response.status == 'success')
{
//your code
}else{
//your code
}
})
.error(function (response) {
console.log('error', response);
});
};
function dataURItoBlob(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {
type: mimeString
});
}
Thanks, the issue was caused by upload and post limit in my php.ini.
I am trying to receive the file sent through AJAX. What's happening is that when the file sent using Chrome/Firefox the file goes to req.files but when it was sent using Safari, the file goes to req.params. The application treat the file as a string "[Object blob]". Thanks.
Sending userdata through ajax.
updatePartnerProfile: function(obj){
var parentObj = this;
var target = $(obj.target);
var parent = target.closest('#editPartnerDetailsForm');
var logoImg = parent.find('.cropped');
var companyLogoBase64 = logoImg.find('.croppedImage').attr('src');
var companyLogo = util.dataURItoBlob(companyLogoBase64);
var userData = new FormData();
userData.append('token', parentObj.token);
userData.append('companyLogo', companyLogo);
$.ajax({
type: 'POST',
url: parentObj.serverUrl + 'api/admin/update/organization/' + parentObj.partnerId,
processData: false,
contentType: false,
cache: false,
data: userData,
success: function(data){
//todo
}
},
error: function(err){
console.log(err);
}
});
},
dataURItoBlob : function(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
if (!_.isUndefined(dataURI)){
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
} else {
return null;
}
}
Am I missing something in the code?
Well, as per this question, you need to be using the buffer property of ia, not just [ia]. Instead of
return new Blob([ia], {type:mimeString});
try
return new Blob([ia.buffer], {type:mimeString});
I want to save a html canvas element as an image using php and jquery ajax.
Here is my code for ajax.
var front_image=canvas.toDataURL("image/png");
//front image is a base_64 string
$.ajax({
url:base_url+'tabs/profile/save_front_image',
type:'POST',
data:'front_image='+front_image,
success:function(response){
}
});
I m just doing echo in php echo $_POST['front_image'] so request and response are same.
When i use this code before ajax it loads image to new tab of browser
var w = window.open('about:blank', 'image from canvas');
w.document.write("<img src='" + frame_image + "' alt='from canvas'/>");
but when i put the same code on ajax response as bellow it doesn't work. Only a blank tab opens in browser. So i m not being able to save image as file.
var w = window.open('about:blank', 'image from canvas');
w.document.write("<img src='" + response + "' alt='from canvas'/>");
I compared string length of frame_image and response also. They are same. I m not sure why image is not loading in response. Please suggest me the answer thanks.
// soon you can use front_image=canvas.toBlob("image/png")
// construct a blob
function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, {type: contentType});
return blob;
}
// make an actually file from the base64 so we can send binary data
var blob = b64toBlob(front_image.split(",")[1], "image/png")
var fd = new FormData();
fd.append("file", blob, "filename.png");
$.ajax({
url: 'http://example.com/script.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
// The saving
<?php
$uploads_dir = '/uploads';
foreach ($_FILES["file"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["file"]["tmp_name"][$key];
$name = $_FILES["file"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>