Download Blob in Safari - download

var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
var data = { x: 42, s: "hello, world", d: new Date() },
fileName = "my-sample.json";
saveData(data, fileName);
The above is working good in chrome and firefox and not in safari as the download attribute of isn't suppoted by safari , anyother idea to overcome this ?

I did a quick research - I looks like Safari does not support what you are trying to achieve.
The reason why your solution works in Chrome (and Firefox) is that they support the download attribute - Safari doesn't yet.

Related

Download file trought tag <a> opens app instead of downloading due to deeplinks

I have an app with deeplinks, where I have declared what is necessary in the manifest and the links are linked to the app. Deeplinks work fine.
The problem comes when I try to download a file, instead of downloading the file it interprets it is a deeplink keeping the view of the app.
For downloading the file I use:
<a href="https://www.myweb.com/Download.php?filename=file.pdf" target="_blank">
Or
function downloadURI(uri, name)
{
var link = document.createElement("a");
link.setAttribute('download', name);
link.href = uri;
document.body.appendChild(link);
link.click();
link.remove();
}
or
function downloadfile(){
$.ajax({
url: 'www.myweb.com/files/filename.pdf',
method: 'GET',
xhrFields: {
responseType: 'blob'
},
success: function (data) {
var a = document.createElement('a');
var url = window.URL.createObjectURL(data);
a.href = url;
a.download = 'myfile.pdf';
document.body.append(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
}
});
}
I try also an Iframe solution:
function shwAtt(strPath) {
var varExt = strPath.split('.');
//alert(varExt.length);
if (varExt[varExt.length - 1] == "txt") {
window.open(strPath);
}
else {
var iframe;
iframe = document.getElementById("hiddenDownloader");
if (iframe == null) {
iframe = document.createElement('iframe');
iframe.id = "hiddenDownloader";
iframe.style.visibility = 'hidden';
document.body.appendChild(iframe);
}
iframe.src = strPath;
}
return false;
}

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

SAPUI5 file upload download gets corrupted

Can someone help me.
I've implemented a file upload / download in UI5 that seems to work but when I download the file it gets corrupted and I can't open it.
For now I'm only testing with image files:
new sap.ui.unified.FileUploader({
buttonOnly: true,
buttonText: "Upload files",
icon: "sap-icon://upload",
change: function(oEvent) {
var oFileUploader = oEvent.getSource();
oItem = oFileUploader.getParent().getParent().getParent();
var sPath = oItem.getBindingContext().getPath();
var files = oEvent.getParameter("files");
var file = files[0];
if (file) {
var oNewFile = {
ID: that.count++,
SurveyAnswerID: oSA.ID,
FileName: oEvent.getParameter("newValue"),
FileBinary: null,
MimeType: "image/jpeg",
Mode: "POST"
};
var reader = new FileReader();
reader.onload = function(evt) {
var binaryString = evt.target.result;
oNewFile.FileBinary = binaryString;
};
reader.readAsBinaryString(file);
} else {
oNewFile.FileBinary = "";
oNewFile.FileName = "";
MessageToast.show("Something went wrong with the file upload.\n Please try again");
}
that._pushItemToFileUploadModel(oNewFile.ID, oNewFile);
that._getFileUploadModel().refresh();
}
})
Download code:
selectionChange: function(oEvent) {
var item = oEvent.getSource().getSelectedItem();
var model = that._getFileUploadModel();
if (item) {
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([item.getDocumentId()], {
type: item.getMimeType()
}));
a.download = item.getFileName();
// Append anchor to body.
document.body.appendChild(a);
a.click();
// Remove anchor from body
document.body.removeChild(a);
}
try {
oEvent.getSource()._oList.removeSelections();
} catch (e) {
//DO nothing
}
},
What an I doing wrong here?
I solved my issue converting the file this way:
var u8_2 = new Uint8Array(atob(data).split("").map(function(c) {
return c.charCodeAt(0);
}));
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([u8_2], {
type: item.getMimeType()
}));

Canvas not showing/drawing anything in Windows Chrome

I have a problem that the code below works in : IE 10, Firefox, Safari, Mac Chrome, but not for Windows Chrome.
$(function () {
var video_dom = document.querySelector('#v');
var canvas_draw = document.querySelector('#c');
var draw_interval = null;
video_dom.addEventListener('play', function () {
video_dom.width = canvas_draw.width = video_dom.offsetWidth;
video_dom.height = canvas_draw.height = video_dom.offsetHeight;
var ctx_draw = canvas_draw.getContext('2d');
draw_interval = setInterval(function () {
ctx_draw.drawImage(video_dom, 0, 0, video_dom.width, video_dom.height);
var dataURL = canvas_draw.toDataURL();
document.getElementById('canvasImg').src = dataURL;
}, 3500)
}, false);
})();
Also I get this error in console like: Uncaught TypeError: object is not a function.
Why is the canvas is working in the Mac version, but not the Windows version of Chrome?
I don't see why you're using a dollar sign ($) in front of your function when you're not using jQuery.
window.onload = function () {
var video_dom = document.querySelector('#v');
var canvas_draw = document.querySelector('#c');
...
};
Should be clear of errors.

Convert Blob to file and pass it as POST parameter XMLHttpRequest

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

Resources