How to save video to Laravel storage folder on Tinymce - laravel

I'd like to save the video I uploaded in the Laravel storage folder, but for now I'm only able to save this away:
<p><video controls="controls" width="300" height="150">
<source src="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGl</video></p>
I would like the url to be
`storage/video-name
.
My current code is this:
file_picker_types: 'media',
file_picker_callback: function(cb, value, meta) {
var input = document.createElement('input');
input.setAttribute('type', 'file');
input.onchange = function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function () {
var id = 'blobid' + (new Date()).getTime();
var blobCache = tinymce.activeEditor.editorUpload.blobCache;
var base64 = reader.result.split(',')[1];
var blobInfo = blobCache.create(id, file, base64);
blobCache.add(blobInfo);
cb(blobInfo.blobUri(), { title: file.name }); // here
};
reader.readAsDataURL(file);
};
input.click(); //here
},
How could I adapt my code so that I can save it in Laravel storage folder?
Laravel version: 8
Tinymce: 5

Related

How can I get the signature from Vue Signature Pad + Laravel

Hi I have read but I have not found the answer so I ask:
How can I get the signature picture?
My Vuejs code is this one:
<VueSignaturePad width="100%" height="500px" ref="signaturePad" />
<div>
<button #click="save">Guardar</button>
<button #click="undo">Borrar</button>
</div>
My methods are:
undo() {
this.$refs.signaturePad.undoSignature();
},
save() {
this.loading = true;
e.preventDefault();
let currentObj = this;
const config = {
headers: { 'content-type': 'multipart/form-data' }
}
let formData = new FormData();
formData.append('signature', this.$refs.signaturePad.saveSignature());
axios.post('/api/signature/store?api_token='+App.apiToken, formData, config)
.then(function (response) {
currentObj.success = response.data.success;
})
}
My Laravel code has this:
$fileName = time().'_'.'signature'.'_'.$this->user->rut.'_'.date('d_m_Y').'.'.$request->file->getClientOriginalExtension();
$signature = new Signature;
$signature->rut = $this->user->rut;
$signature->signature = $fileName;
$signature->save();
Storage::disk('dropbox')->putFileAs(
'signatures/',
$request->file,
$fileName
);
The problem is that it displays me an error:
Call to a member function getClientOriginalExtension() on null
So I wonder how can I get the image?
this option worked for me to convert the base64 file to image before sending it
Vue code
<div id="app">
<vueSignature ref="signature" :sigOption="option" :w="'800px'" :h="'400px'" :disabled="disabled"></vueSignature>
<vueSignature ref="signature1" :sigOption="option"></vueSignature>
<button #click="save">Save</button>
<button #click="clear">Clear</button>
<button #click="handleDisabled">disabled</button>
</div>
functions
save(){
var _this = this;
var png = _this.$refs.signature.save()
var block = png.split(";");
// Get the content type of the image
var contentType = block[0].split(":")[1];// In this case "image/gif"
// get the real base64 content of the file
var realData = block[1].split(",")[1];// In this case "R0lGODlhPQBEAPeoAJosM...."
// Convert it to a blob to upload
var blob = this.b64toBlob(realData, contentType);
let data = new FormData()
data.append('img', blob)
axios.post(this.url, data).then(res=>{
console.log(res.data)
}).catch(function (error) {
console.log(error.response)
})
},
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;
},
I hope I've helped

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

Binding Images to Image placeholder in repeater

I have a repeater that loads info from SQLite and works well. The user has options to take photos which are stored both in their photo library and in a temp folder. On reloading the page I need to reload the images to for a sliding gallery of thumbnails under the relevant section in the repeater.
The Image repeater is defined as
<Repeater items="{{ images }}" id="{{ repeaterphotoid }}">
<Repeater.itemTemplate>
<Image src="{{localurl}}" width="75" height="75" visibility="{{photoevidence === 'y' ? 'visible' : 'collapse'}}" />
</Repeater.itemTemplate>
</Repeater>
And my code is
exports.takePic = function(args){
var page = args.object;
camera.requestPermissions().then(
function success(){
var livesite = appSettings.getString("livesite");
var images=[];
var whichcamera = args.object;
var options = {saveToGallery: true, keepAspectRation: true, height: 1024 };
var gallery = args.object.page.getViewById("images-"+whichcamera.id);
var source = new imageSourceModule.ImageSource();
camera.takePicture(options).then(function(imageAsset){
var img = new imageModule.Image();
source.fromAsset(imageAsset).then((imageSource) => {
var auditDB = new sqlite("my.db", function(err, db){
if (err){
alert("Failed to open the database", err);
} else {
var tempfilename = livesite+"-"+whichcamera.qid+"-";
db.all("SELECT filename FROM images WHERE filename LIKE '"+tempfilename+"%'").then(rows =>{
//console.log("Images rows="+rows.length+1);
if (rows.length == 0){
imageCount = 1;
}
else
{
imageCount = rows.length+1;
}
var livesite = appSettings.getString("livesite");
// var path = filesystem.path.join(filesystem.knownFolders.documants().path,"photos")
var folder = filesystem.knownFolders.documents();
var filename = livesite+"-"+whichcamera.qid+"-"+imageCount+".jpg";
var imgPath = filesystem.path.join(folder.path,filename);
var saved = imageSource.saveToFile(imgPath,"jpg");
if (saved){
var livesite = appSettings.getString("livesite");
var liveaudit = appSettings.getString("liveaudit");
db.execSQL("INSERT INTO images (localurl,remoteurl,syncd,siteid,filename,question) VALUES(?,?,?,?,?,?)",[imgPath,'-','n',livesite,filename,whichcamera.qid])
var imageList = [];
var tempfilename = livesite+"-"+whichcamera.qid+"-";
var imageSQL = "SELECT localurl,remoteurl,filename FROM images WHERE filename LIKE '"+tempfilename+"%'";
db.all(imageSQL).then(rows =>{
for (var row in rows) {
imageList.push({
localurl: rows[row][0],
filename: rows[row][2]
});
}
const imagesource = fromObject({
images: imageList
});
imagesource.set = ("images", imageList);
var imageholder = args.object.page.getViewById("repeat_"+whichcamera.id);
imageholder.bindingContext = imagesource;
});
};
});
};
});
});
}).catch(function (err) {
alert("Camera Error "+err.message);
})
//alert("Taking Pic with camera "+whichcamera.id);
},
function failure(){
alert("You must allow this app access to the camera and your photos library.")
});
}
Binding to the questions works as expected but I cannot bind the images to the image repeater, nothing happens. Obviously missing something but going code blind.

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

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