Saving images uploaded using ImagesLoader - javascript

I am trying to wire up the ImagesLoader plugin, which allows uploading multiple images. It has a nice drag-n-drop UI but I just can't figure out how to get the images that were uploaded. I cannot find any documentation.
Link to the plugin page: ImagesLoader
Here is the javascript from the demo:
<script type="text/javascript">
// Ready
$(document).ready(function () {
// Create image loader plugin
var imagesloader = $('[data-type=imagesloader]').imagesloader({
minSelect: 3
,imagesToLoad: [{"Url":"./img/Nespresso001.jpg","Name":"Nespresso001"},{"Url":"./img/Nespresso002.jpg","Name":"Nespresso002"}]
});
//Form
$frm = $('#frm');
// Form submit
$frm.submit(function (e) {
var $form = $(this);
var files = imagesloader.data('format.imagesloader').AttachmentArray;
var il = imagesloader.data('format.imagesloader');
if (il.CheckValidity())
alert('Upload ' + files.length + ' files');
e.preventDefault();
e.stopPropagation();
});
});
The images are saved in the object "files". Here is a screen shot of the contents from the inspector:
I tried converting to json and posting, but that only generates an error.
$.ajax({
url: 'process-images.php',
type: 'POST',
data: JSON.stringify(files),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
cache: false,
error: function() {alert("ERROR");},
success: function() {alert("OK");}
});
The rest of the code works just like the demo. Looks like everything needed for the uploaded images is stored in "files". I just need to get the data back to php and I can pull it apart from there. But right now, the original submit code just dies or my addition aborts with an error.
THANKS!

I hope it is not too late to answer.
You just need to loop through the base64 encoded image object, decoding and saving each image to the disk.
// Sample code
foreach(json_decode($request->input('files')) as $file) {
$name = $file->FileName
$imagePath = storage_path('app/public/images/');
file_put_contents($imagePath.$name, base64_decode($file->Base64));
}

Related

Uploading and handling images in SharePoint

I have a custom form on a SharePoint list in which the user uploads an image and a caption.
There is a PowerPoint slide with a template where the image should then go and the caption below it. Ideally I want the uploaded image to be taken from the SharePoint list and automatically input to the PowerPoint slide with the caption. The slide should then be saved as an image file and uploaded to SharePoint picture library to enable it to be used in a picture library slideshow on the homepage.
Does anyone have any idea how to do this or any other ways in which this may be possible.
I have tried using a combination of JavaScript and html with no luck.
You can use the SharePoint REST API to retrieve the image and caption from the SharePoint list, then use the Microsoft Graph API to add the image and caption to the PowerPoint slide template. Once the slide is updated, you can use the Microsoft Graph API to convert the slide to an image file and then upload the image file to the SharePoint picture library using the SharePoint REST API. You can use a programming language such as Python or JavaScript to automate this process.
You can refer to following code to upload pic to sharepoint by rest api and js
var fileInput = jQuery('#getFile');
var file = fileInput[0].files[0];
var serverRelativeUrlToFolder = '*****'; //if the library in subsite, You have to remove the forward slash "/" before the document library relative url.
proccessUploadUsingJQueryAjax(file, serverRelativeUrlToFolder);
function getFileBuffer(file) {
var deferred = jQuery.Deferred();
var reader = new FileReader();
reader.onloadend = function (e) {
deferred.resolve(e.target.result);
}
reader.onerror = function (e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(file);
return deferred.promise();
}
function addFileToFolderUsingJQueryAjax(fileName, arrayBuffer, serverRelativeUrlToFolder) {
// Construct the endpoint.
var fileCollectionEndpoint = String.format(
"{0}/_api/web/GetFolderByServerRelativeUrl('{1}')/files/add(overwrite=true, url='{2}')",
_spPageContextInfo.webAbsoluteUrl, serverRelativeUrlToFolder, fileName);
// Send the request and return the response.
// This call returns the SharePoint file.
return jQuery.ajax({
url: fileCollectionEndpoint,
type: "POST",
data: arrayBuffer,
processData: false,
contentType: "application/json;odata=verbose",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
}
});
}
function proccessUploadUsingJQueryAjax(file, serverRelativeUrlToFolder){
var getFile = getFileBuffer(file);
getFile.done(function (arrayBuffer) {
// Add the file to the SharePoint folder.
var addFile = addFileToFolderUsingJQueryAjax("image.jpg", arrayBuffer, serverRelativeUrlToFolder);
addFile.done(function (file, status, xhr) {
alert("File Uploaded");
});
addFile.fail(function (error) { alert("Error Add File: " + error.responseText); });
});
getFile.fail(function (error) { alert("Error Get File: " + error.responseText); });
}

Appended files to FormData not received at Laravel server

I'm facing a strange issue ... I've a form with multiple fields .. on form submit, I append multiple image files to form data and submit it like this:
$('#newEntry').on('submit', function(e){
e.preventDefault();
const formData = new FormData(e.target);
formData.delete('images[]');
for (var i = 0; i < filesToUpload.length; i++) {
formData.append('images[]', filesToUpload[i].file, filesToUpload[i].file.name);
}
$(this)[0].submit();
});
and when I try to echo(count($request->images)) at Laravel server it echos 0 .. and on dd($request) .. I see empty files array
but when I submit same form with same files directly from input field instead of appending data to it like this:
<input type="file" name="images[]">
I receive all files at server.
Files are successfully appended to formData .. I've checked it by:
var formKeys = formData.keys();
var formEntries = formData.entries();
do {
console.log(formEntries.next().value);
} while (!formKeys.next().done)
I've also tried to send same appended files through AJAX and it worked perfectly fine:
$('#newEntry').on('submit', function(e){
e.preventDefault();
const formData = new FormData(e.target);
formData.delete('images[]');
for (var i = 0; i < filesToUpload.length; i++) {
formData.append('images[]', filesToUpload[i].file, filesToUpload[i].file.name);
}
$.ajax({
url: actionURL,
data: formData,
processData: false,
contentType: false,
type: "POST",
success: function (data) {
alert("DONE");
},
error: function (data) {
alert("ERROR - " + data.responseText);
}
});
});
on digging down deeper .. I've found that when I submit a form via Http request an Error with code 500 Internal Server Error appears in console for a moment (just before page reloads)
tried everything but don't know what is causing this strange behavior .. kindly help me sort it out
You can check the network tab of your browser(Preferably Chrome) to compare the request parameters that you send to the server.
If the request is too fast that you can't capture it, try placing debugger;(Or click on the in front of the line of code in the source tab) into your Javascript code to stop the execution of the code right before it reload. Then you can inspect the current state of your Javascript and also the 500 response that you received.

Error image loading in Fabric.js (canvas.loadFromJSON)

I am trying to load a previously saved database of the canvas. I get an error "error loadinghttp://flysite.byethost31.com/wp-content/plugins/coderisimo_diagram_constructor/user_images/rqtJkb.jpg" , But only in chrome. In firefox everything is working fine. The picture that the script can not load available. Link correctly. Thank you.
jQuery('body').on('click', '.di-links', function () {
var id = jQuery(this).attr('di-id');
jQuery.ajax({
type: 'POST',
url: base_url,
data: {'diagram_id': id, 'action': 'get_user_diagram'}
}).done(function (json) {
var data = JSON.parse(json);
canvas.loadFromJSON(data.diagram, canvas.renderAll.bind(canvas));//ERROR
jQuery('#diagram-title').val(data.title);
id_loaded_diagram = id;
});
video - https://dl.dropboxusercontent.com/u/19954007/WHY.mp4
Help!!!

Im not able to decode my file passed from JAVASCRIPt to PHP

I am encoding and passing a file (word document) to php.How can I read this and write to a file?
I have submit button.On submit, I am passing an ajax.Before that, Iam encoding the file with file reader.On submit button, an event 'handleFileSelect' is trtiggered.The file is read as dataurl and sent to php via ajax.
I am able to get the data as encoded.If the file is a text, i am also able to decode .But
its not able to get the contents of a word file.If I decode
How would I do this?
My code :
//File Convertion--Function to convert images to base 64 encoded format
function handleFileSelect(objEvent) {
var strFiles = objEvent.target.files; // FileList object
strInput = document.getElementById('uploaded_file');
strFile = strInput.files[0];
strFiletype=strFile.type;
strFileSize=strFile.size;alert(strFiletype);
strFiletype=strFiletype.split("/");
//Checking wheter the uploaded file is image or not
if(strFiletype[0]!='image') {
for (var i = 0, f; f = strFiles[i]; i++) {
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
strGlobalImageData=e.target.result;
};
})(f);
reader.readAsDataURL(f);
}
} else {
alert("NOT A DOC");
}
}
//ajax call to send files to php
var app = 'contact.php';
$.ajax({
url: app,
async: false,
type:"POST",
data : "file="+strGlobalImageData,
dataType: "jsonp",
contentType: 'application/x-www-form-urlencoded',
processData:false,
jsonp: "jsoncallback",
success: function(html) {
alert("Thank you. We will be in touch with you");
},
error: function(){
alert("Thank you. We will be in touch with you");
}
});
//Php side--contact.php
<?php
$files=base64_decode($_POST['file']);
If I decode, I am getting a binary format of the word file
The issue was with character replacing.We need to replace befor decoding the data.The exact code is shown below:
In Php,
$files=trim($_POST['file']);
$strEncodedData= str_replace(' ','+',$files);
$strFilteredData = explode(',',$strEncodedData);
$strDecodedData= base64_decode($strFilteredData[1]);
$arrFiles = explode(",",$files);
file_put_contents("myfile.doc",$strDecodedData);
This content will be written into file "myfile.doc".
Thank you for all effort made by my friends

Can't save image via HTML canvas

I'm having difficulties saving my canvas. I'm new to javascript so I think it could be a syntax issue.
I've got some vars saved in a function:
var imageView = document.getElementById("imageView");
var canvasData = imageView.toDataURL("image/png");
var postData = "canvasData="+canvasData;
If I add the following line it displays the image correctly:
imgData = $('#i').append($('<img/>', { src : canvasData }));
However, I have another function that I want to pass the base64 code in so I added:
var the_data = "test= "+imageView.toDataURL("image/png");
It does print out a base64 code, but just the blank canvas (not with the drawing the user has added).
If I add the following it doesn't work:
var the_data = "test= "+canvasData;
What am I doing wrong?
This is a basic jsfiddle of what I'm trying to do: http://jsfiddle.net/sMSeX/
Just a little hint from my side for uploading HTML5 canvas image data:
I am working on a project for a print-shop and had some problems due to uploading images to the server that came from an HTML5 canvas element. I was struggling at least for one hour and I did not get it to save the image correctly on my server.
I get the image data as Base64 decoded from the canvas element via
var can = document.getElementsByTagName('canvas');
var dataURL = can[0].toDataURL("image/jpg");
//dataURL = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
console.log('data url: '+dataURL);
Once I set the
contentType option of my jQuery ajax call to 'application/x-www-form-url-encoded' :
$.ajax({
url: 'index.php?page=upload-image',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
//data: '{ "imageData" : "' + dataURL + '" }',
data: dataURL,
beforeSend: function() {
$('.text-danger').remove();
},
complete: function() {
},
success: function(json) {
console.log('upload complete');
}
});
everything went the right way and the base64-encoded data was interpreted correctly and successfully saved as an image.
Maybe someone helps that!

Categories