Convert Blob to file and pass it as POST parameter XMLHttpRequest - ajax

//photo - image in Blob type
//no problems with it, checked with FileReader.readAsDataURL & <img>
var form = new FormData()
form.append('file1', photo, 'image.jpg')
ajax.post(url, form, callback) //no photos uploaded
Documentation of what I am trying to do: Uploading Files to the VK Server Procedure (step 2)
So, how should I pass my blob as POST parameter?
Image of the request

A complete File Upload exampe found at Mozilla Developer Network
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications#Example.3A_Uploading_a_user-selected_file
You use FileReader.readAsBinaryString() to read the data and then XHR sendAsBinary() to push IO forward
function FileUpload(img, file) {
var reader = new FileReader();
this.ctrl = createThrobber(img);
var xhr = new XMLHttpRequest();
this.xhr = xhr;
var self = this;
this.xhr.upload.addEventListener("progress", function(e) {
if (e.lengthComputable) {
var percentage = Math.round((e.loaded * 100) / e.total);
self.ctrl.update(percentage);
}
}, false);
xhr.upload.addEventListener("load", function(e){
self.ctrl.update(100);
var canvas = self.ctrl.ctx.canvas;
canvas.parentNode.removeChild(canvas);
}, false);
xhr.open("POST", "http://demos.hacks.mozilla.org/paul/demos/resources/webservices/devnull.php");
xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');
reader.onload = function(evt) {
xhr.sendAsBinary(evt.target.result);
};
reader.readAsBinaryString(file);
}

Related

convert .heic image to jpg image format in laravel

I have added intervention/image package to convert image format in laravel.
image converted successfully but after uploading image quality was so bad.
Original Image
Uploaded Image
$img =(string) Image::make($image['base64'])
->resize(500, 500)->encode('jpg',100);;
$img = base64_encode($img);
To convert Heic image you have to use imagick, can you use this instead
This is how to install https://ourcodeworld.com/articles/read/645/how-to-install-imagick-for-php-7-in-ubuntu-16-04
try {
$image = new \Imagick();
$image->readImageBlob($image['base64']));
$image->setImageFormat("jpeg");
$image->setImageCompressionQuality(100);
$image->writeImage($targetdir.$uid.".jpg");
}
catch (\ImagickException $ex) {
/**#var \Exception $ex */
return new JSONResponse(["error" => "Imagick failed to convert the images, check if you fulfill all requirements." , "details" => $ex->getMessage()], Http::STATUS_INTERNAL_SERVER_ERROR);
}
A bit late, but I had the same problem.
I managed to do it with the heic2any js library (https://github.com/alexcorvi/heic2any/blob/master/docs/getting-started.md)
I converted the picture on client side, then gave it to the input in client side.
Server is seeing it as it was originally uploaded as jpg.
function convertHeicToJpg(input)
{
var fileName = $(input).val();
var fileNameExt = fileName.substr(fileName.lastIndexOf('.') + 1);
if(fileNameExt == "heic") {
var blob = $(input)[0].files[0]; //ev.target.files[0];
heic2any({
blob: blob,
toType: "image/jpg",
})
.then(function (resultBlob) {
var url = URL.createObjectURL(resultBlob);
$(input).parent().find(".upload-file").css("background-image", "url("+url+")"); //previewing the uploaded picture
//adding converted picture to the original <input type="file">
let fileInputElement = $(input)[0];
let container = new DataTransfer();
let file = new File([resultBlob], "heic"+".jpg",{type:"image/jpeg", lastModified:new Date().getTime()});
container.items.add(file);
fileInputElement.files = container.files;
console.log("added");
})
.catch(function (x) {
console.log(x.code);
console.log(x.message);
});
}
}
$("#input").change(function() {
convertHeicToJpg(this);
});
What I am doing is converting the heic picture to jpg, then previewing it.
After that I add it to the original input. Server side will consider it as an uploaded jpg.
Some delay can appear while converting, therefore I placed a loader gif while uploading.
The heic2any js library helped me accomplish this (https://github.com/alexcorvi/heic2any/blob/master/docs/getting-started.md)
On the client side, I converted the picture, then gave it to the server input. The server sees it as it was originally uploaded as PNG.
$('#files').on('change' , function(){
var total_file=document.getElementById("files").files.length;
for(var i=0;i<total_file;i++)
{
files = event.target.files[i];
var fileName = files.name;
var fileNameExt = fileName.substr(fileName.lastIndexOf('.') + 1);
objURL = URL.createObjectURL(event.target.files[i]);
if(fileNameExt == "heic") {
objURL = await convertHeicToJpg(input , i);
}
})
async function convertHeicToJpg(input , i)
{
var blobfile = $(input)[0].files[i]; //ev.target.files[0];
let blobURL = URL.createObjectURL(blobfile);
// convert "fetch" the new blob url
let blobRes = await fetch(blobURL)
// convert response to blob
let blob = await blobRes.blob()
// convert to PNG - response is blob
let resultBlob = await heic2any({ blob })
console.log(resultBlob)
var url = URL.createObjectURL(resultBlob);
let fileInputElement = $(input)[0];
let container = new DataTransfer();
let file = new File([resultBlob], "heic"+".png",{type:"image/png", lastModified:new Date().getTime()});
container.items.add(file);
fileInputElement.files[0] = container.files;
uploadFile(container.files);
console.log("added");
console.log(url);
return url ;
}
function uploadFile(files)
{
console.log(files);
var error = '';
var form_data = new FormData();
for(var count = 0; count<files.length; count++)
{
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
form_data.append("files[]", files[count]);
}
$.ajax({
url:"<?php echo base_url(); ?>Property/upload",
method:"POST",
data:form_data,
contentType:false,
cache:false,
processData:false,
dataType:'JSON',
beforeSend:function(){
//..processing
},
success:function(data)
{
alert('image uploade')
}
})
}

404 error to show image from firebase storage

I want to show uploaded image,but I got 403 error even I signin.
Uploading work well, and downloadURl is ok.
And I authenticated already (Upload success shows that I already signined)
but I can't show uploaded image.
storage.child(file_name).put(event_image).then(function(snapshot) {
console.log('Uploaded a blob or file!');
var img_src = snapshot.downloadURL;
$('img#uploaded').attr('src',img_src);
});
Use this link: https://firebase.google.com/docs/storage/web/download-files#download_data_via_url
storageRef.child('images/stars.jpg').getDownloadURL().then(function(url) {
// `url` is the download URL for 'images/stars.jpg'
// This can be downloaded directly:
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
// Or inserted into an <img> element:
var img = document.getElementById('myimg');
img.src = url;
}).catch(function(error) {
// Handle any errors
});

Why are files are different when downloading from an ASP.NET (AJAX download with Blob)

Using MVC 4.0, I have used the following code to create a download files from the server from an ajax source (using the latest firefox):
This works fine if the output involves are textual files such as csv or txt files, however, when it comes to files like zip or xlsx, it seems the downloaded file is different from the original source (i.e. the zip generated within the server are 15K, but the one downloaded are 26K)
I have been struggling for a few days, can I ask if anyone should shred some light on why it will works for csv/text files, but not for zip or xlsx files?
Many thanks
Controller:
Public Function download(dataIn As myObject) As ActionResult
'some processing
'generated zip files and return with the full path
Dim zipFullPath = generateFiles(dataIn)
Response.Clear()
Response.ContentType = "application/zip"
Response.AddHeader("Content-Disposition", "attachment; filename=Out.zip")
Dim fileLength = New IO.FileInfo(zipFullPath).Length
'fileLength reads about 15K of data
Response.AddHeader("Content-Length", fileLength)
Response.TransmitFile(zipFullPath)
Response.End()
Return View()
End Function
JavaScript:
$.ajax({
type: "POST",
url: "reports/download",
data: jData,
contentType: "application/json; charset=utf-8",
success: function(response, status, xhr) {
// check for a filename
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
var type = xhr.getResponseHeader('Content-Type');
var blob = new Blob([response], { type: type });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
//Here is the problem, the original is about 15k,
// but the download file is about 26K
}
} else {
window.location = downloadUrl;
}
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
}
},
error: function (data) {
alert('Error');
}
});
Currently jQuery ajax can only process text responses, that's why your text files work but your binary files fail.
To download a non text file from ajax use the XMLHttpRequest object and specify a responseType, for instance blob or arraybuffer.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
...
var blob = this.response; //save the blob as usual
...
}
}
xhr.open('POST', 'reports/download');
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.responseType = 'blob'; // the response will be a blob and not text
xhr.send(jData);

Action is not being called in XMLHttpRequest

I am trying to upload a file by XMLHttpRequest. After uploading I am trying to show preview of the image by calling an action as a source of the image.
Here is the code sample:
var xhr = new XMLHttpRequest();
xhr.file = file;
xhr.onreadystatechange = function (e) {
if (this.readyState == 4 && xhr.status == 200) { // here I am updating the image source
document.getElementById('imagePreview').src = '#Url.Action("GetTPImaegeByName","Techpack",new { area="OMS" })';
}
};
xhr.open('post', 'someurl', false);
var fd = new FormData;
fd.append('photo', file);
xhr.send(fd);
Here #Url.Action("GetTPImaegeByName","Techpack",new { area="OMS" }) returns an image file.
For the first time the source of the image is updating and shown correctly. But if I try again to change the file the it doesn't work. Looks like the action to update the image source is not being called. Need help to solve this problem.

JavaScript Blob Upload with FormData

I am having a problem uploading a blob created in javascript to my server. The basic idea is that a user uploads an image and in javascript I center crop the image and downsample it before transmission.
The image manipulation is working fine, but the upload itself is not working right. Here is the code that does the upload and conversion from canvas to blob
function uploadCanvasData()
{
var canvas = $('#ImageDisplay').get(0);
var dataUrl = canvas.toDataURL("image/jpeg");
var blob = dataURItoBlob(dataUrl);
var formData = new FormData();
formData.append("file", formData);
var request = new XMLHttpRequest();
request.onload = completeRequest;
request.open("POST", "IdentifyFood");
request.send(formData);
}
function dataURItoBlob(dataURI)
{
var byteString = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++)
{
ia[i] = byteString.charCodeAt(i);
}
var bb = new Blob([ab], { "type": mimeString });
return bb;
}
The server claims that no files were uploaded, and when I use chrome to examine the request, I see the request payload as:
------WebKitFormBoundaryyzYbm61DKgS09tpB
Content-Disposition: form-data; name="file"
[object FormData]
------WebKitFormBoundaryyzYbm61DKgS09tpB--
In contrast to the payload of a form being submitted with input type="file"
------WebKitFormBoundaryUOn3WXb7pKLmOxRZ
Content-Disposition: form-data; name="imagefile"; filename="-3YQHiVaGWo.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryUOn3WXb7pKLmOxRZ--
So it looks to me like the XMLHttpRequest is just uploading the result of calling blob.toString()
Does anyone know what I am doing wrong here? Is there a better approach I should be using?
You have a typo in the function uploadCanvasData it should read
formData.append("file", blob);
Read your code more carefully!
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
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});
}
create an xmlhttpRequest
let uriPost ="active.php";
let xhrPost =new XMLHttpRequest();
then do this it easy
var dataURL = canvas.toDataURL('image/jpeg', 0.5);
var blob = dataURItoBlob(dataURL);
var fd = new FormData(document.forms[0]);
fd.append("canvasImage", blob);
I hope you'l do all this in a function that you will create your self then call that function

Resources