I am having an issue with my file upload from javascript to laravel and displaying it for later use, below is my code to upload and save to db and retrieve later and display it
$(document).on("change", "#facesheet", function() {
handleFileSelect($(this));
});
function handleFileSelect(evt) {
var files = $(evt)[0].files; // FileList object
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var fileString = e.target.result;
$("#divFileUpload").removeData("file");
$("#divFileUpload").removeData(
"filename");
$("#divFileUpload").removeData("extension");
$("#divFileUpload").data("file", fileString);
$("#divFileUpload").data(
"filename", theFile.name);
$("#divFileUpload").data("extension", theFile
.name.split('.').pop().toLowerCase());
};
})(f);
reader.readAsDataURL(f);
}
}
on submit button in modal, this code will execute and saves to db using base64_encode object and stores as blob
function uploadpdf() {
var $formdata = {
'data': $("#divFileUpload").data("file"),
'filename': $("#divFileUpload").data("filename"),
'type': $("#divFileUpload").data("extension"),
'Number': $("#hdnNumber").val()
};
$.ajax({
url: '/upload',
type: 'POST',
data: $formdata,
success: function(response) {
alert("Uploaded successfully");
window.location.reload();
}
});
return false;
}
when a user click on the uploaded file it opens a new window to display the file. Everything works fine with this as long as pdf contains text data but when pdf is completely an image then it wont display anything, any help will be appreciated on this.
Related
I have a wizard with different forms on every step. In one of the steps I have cropper for images and on next step I want to send crop data to controller method but I can't add that to serializeArray. This is my js part:
wizard.on('beforeNext', function (wizardObj) {
wizardObj.stop();
let wizardForm = $('#kt_form_' + wizardObj.currentStep)
let dataForm = wizardForm.serializeArray()
if (wizardObj.currentStep == 2) {
canvas = cropper.getCroppedCanvas({
width: 160,
height: 160,
});
canvas.toBlob(function (blob) {
url = URL.createObjectURL(blob);
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
var base64data = reader.result;
dataForm.push({ name: "cropImage", value: base64data });
}
});
}
let url = wizardForm.attr('action')
let method = wizardForm.attr('method')
$.ajax({
url: url,
type: method,
data: dataForm,
}).done(function (response) {
wizardObj.goNext();
})
When I console log a dataForm I see that I have cropImage attribute but on controller method it's not part of request when I dd($request->all())
I am trying to convert .HEIC image to .JPG using libheif.
libheif converts image on client side browser window only. So in order to save the image i converted image to base64 and then performed ajax to save the image using file_put_contents.
this.canvas.toBlob(function(blob) {
var extension = FILE_EXTENSIONS[blob.type] || ".bin";
var basename = this.filename.replace(/\.[^/.]+$/, "");
if (navigator.msSaveOrOpenBlob) {
navigator.msSaveOrOpenBlob(blob, basename + extension);
return;
}
var readers = new FileReader();
var base64image;
readers.readAsDataURL(blob);
readers.onload = function () {
var base64image = readers.result; // data <-- in this var you have the file data in Base64 format
// console.log(base64image);
// call ajax
var formData = new FormData();
formData.append('filename', basename);
formData.append('avatar', readers.result);
$.ajax('upload.php', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function (response) {
console.log(response);
},
error: function () {
}
});
};
return;
// this.downloads.appendChild(dlink);
// dlink.click();
// URL.revokeObjectURL(url);
}.bind(this), format);
When i convert a single image then it works fine. But if i try to convert in loop it does not works.
Before completing js conversion, my php loop runs (I think this is the issue) So i tried php function sleep() and js set timeout(), But unfortunately none worked.
(function() {
var demo = new HeifDemo(libheif);
<?php $img_array = array('demo/1.heic', 'demo/2.heic', 'demo/3.heic');
foreach ($img_array as $img) : ?>
function saveImage(subject, callback) {
demo.loadUrl(subject);
callback();
}
saveImage('<?php echo $img; ?>', function() {
// demo.saveImage();
setTimeout( function(){
demo.saveImage();
}, 2500 );
});
//});
<?php sleep(4); endforeach; ?> }).call();
so I have this code to upload an image and show it's preview. It also allows you to upload multiple images and show it's preview.
However, how can I actually push this image to server now? I've tried this but it doesnt seems to be working.
HTML
<input type="file" name="albumPics" id="albumPics" style="display:none;" multiple="multiple" />
javascript
window.onload = function(){
//Check File API support
if(window.File && window.FileList && window.FileReader)
{
var filesInput = document.getElementById("albumPics");
filesInput.addEventListener("change", function(event){
var files = event.target.files; //FileList object
var output = document.getElementById("albumPicsPreview");
for(var i = 0; i< files.length; i++)
{
var file = files[i];
alert(file);
//Only pics
if(!file.type.match('image'))
continue;
var picReader = new FileReader();
picReader.addEventListener("load",function(event){
var picFile = event.target;
var liContent = "<li><img style='height: 195px;' src='" + picFile.result + "'" + "title='" + picFile.name + "'/></li>";
$("#albumPicsPreview").prepend(liContent);
// output.html(div);
// upload the image
$.ajax({
type: "POST",
url: "pettyURL.php",
data: file,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
dataType: "json",
success: function(response)
{
// some code after succes from php
console.log("success");
},
beforeSend: function()
{
// some code before request send if required like LOADING....
}
});
}); //event listener
//Read the image
picReader.readAsDataURL(file);
}
});
}
else
{
console.log("Your browser does not support File API");
}
}
The ajax doesn't work here. It seems no data goes to the PHP file. How can I make it work?
I've coded a javascript code which nicely collects every file user wants to upload. But things turned when I added drag/drop file option.
By default, I had a code which monitored input[type='file'] change event handler and once it was detected, actions were performed and files were sent to server for upload.
But since drag/drop doesn't change the input[type='file'] value and neither I can change it programmatically due to security reasons, I'm struck how do I send files which are dragged and dropped on the site.
Here's some of my code:
document.getElementById('drop').addEventListener('drop', function (e) {
e = e || window.event;
e.preventDefault();
var dt = e.dataTransfer;
var files = dt.files;
for (var i=0; i<files.length; i++) {
var file = files[i];
var reader = new FileReader();
reader.readAsDataURL(file);
addEventHandler(reader, 'loadend', function(e, file) {
var bin = this.result;
var filename = file.name;
var filesize = (file.size/1048576).toFixed(2) + ' MB';
alert(' '+filename+' '+filesize+' '); // DEBUGGING ONLY
console.log("YEAY");
if(filecheck(filename)) { // Additional Function
step2(filesize, filename, bin); // Additional Function
$('.btn').click(function() { // Button to be clicked to start upload
$('#main_img_upload').submit(); // Form with that input[type='file']
});
}
else {
alert("Wrong File");
return false;
}
}.bindToEventHandler(file), false);
}
return false;
});
Obviously, it starts upload but server doesn't receive anything as no change has been made to form. But I have all the necessary details (name of file, size of file, etc..)
Any help would be appreciated.
Try out this code.
data.append("FileName", files[0]);
$.ajax({
url: "../",
type: "POST",
processData: false,
contentType: false,
data: data,
success: function (data) {
if (data) {
}
},
error: function (er) {
MSGBox(er);
}
});
}
Problem:
I have the Url (eg. http://files.parse.com/../../..jpg ) of the uploaded file and it's fileName, and now need to retrieve the corresponding file from that Url(Parse.com) by using Only via Javascript . Any one have the answer let me know. Thank you very much!
Code: (upload):
function uploadFn(fileName,fileType,fileData,c){
var parseUrl='https://api.parse.com/1/files/'+fileName;
$.ajax({
type:'post',
beforeSend:function(req){
req.setRequestHeader('X-Parse-Application-Id',myParseAppId);
req.setRequestHeader('X-Parse-REST-API-Key',myParseRestApiId);
req.setRequestHeader('Content-Type',fileType); // fileType always == 'image/jpg;'
},
url:parseUrl,
data:fileData,
processData:false,
contentType:false,
success:function(rslt){
if(rslt){
alert('Upload success\n Filename:'+rslt.name+'\n Url:'+rslt.url);
imgObj.save({curUser:curUser,fileName:rslt.name,fileUrl:rslt.url,fileId:c},
{success:function(succ){
alert('File info saved!');
},error:function(err){
alert('Error:'+err.code);
}
}) // save
}
},
error:function(err){
//var errObj=jQuery.parseJSON(err);
alert('Error:'+err.responseText);
}
});
}
upload is not a problem. It works fine! Only for retrieving from Parse.com
(toRetrieve) [I tried as: ]
function fetchImg(url){
$.ajax({
url:url,
async:false,
type:'POST',
beforeSend:function(req){
req.setRequestHeader('X-Parse-Application-Id',myParseAppId);
req.setRequestHeader('X-Parse-REST-API-Key',myParseRestApiId);
req.setRequestHeader('Content-Type','image/jpg');
},
complete:function(rslt){
$('#imgId').attr('src','data:image/jpg;base64,'+rslt.responseText);
},
success:function(){//Success
},
error:function(err){
alert('Error: '+err.responseText+'\nStatus: '+err.statusText);
}
})
}
[output:]
'Error-msg>The specified method not allowed against this resouce' Status: Method Not allowed!.
Notes: ¤ (I saved the fileName, fileUrl to the Parse DataBrowser, and used this for try to retrieve the uploaded file.)
¤ (App is based on 'Phonegap')
¤ Im novice to Parse/Javascript.
Thanks a lot! *
Check here: Load contents of image from camera to a file
basically: with the info in this post. . Big thanks to Raymond Camden!
function gotPic(data) {
window.resolveLocalFileSystemURI(data, function(entry) {
var reader = new FileReader();
reader.onloadend = function(evt) {
var byteArray = new Uint8Array(evt.target.result);
var output = new Array( byteArray.length );
var i = 0;
var n = output.length;
while( i < n ) {
output[i] = byteArray[i];
i++;
}
var parseFile = new Parse.File("mypic.jpg", output);
parseFile.save().then(function(ob) {
navigator.notification.alert("Got it!", null);
console.log(JSON.stringify(ob));
}, function(error) {
console.log("Error");
console.log(error);
});
}
reader.onerror = function(evt) {
console.log('read error');
console.log(JSON.stringify(evt));
}
entry.file(function(s) {
reader.readAsArrayBuffer(s);
}, function(e) {
console.log('ee');
});
});
}
I think to retrieve the image method should be GET instead of POST for your ajax request.