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); });
}
Related
I have a canvas image generated by some JS on my page that I'm trying to upload to my server using Laravel, my controller code:
public function imageUploadAPI(Request $request)
{
$imageName = time().'.'.$request->image->getClientOriginalName();
$request->image->move('/home/XXXXX/storage/app/public/images/'.$request->project_id.'/'.$request->report_id.'/', $imageName);
return response()->json(['success'=>['You have successfully upload image.'],'image'=>[$request->project_id.'/'.$request->report_id.'/'.$imageName]]);
}
Im trying to send in as a blob but it did NOT work, any ideas?
my code:
function uploadImage() {
var canvas = document.getElementById('snapshot');
canvas.toBlob((blob) => {
const newImg = document.createElement('img');
const url = URL.createObjectURL(blob);
newImg.onload = () => {
URL.revokeObjectURL(url);
};
var formdata = new FormData($("#addForm")[0]);
formdata.append('image', url);
$.ajax({
url : "/api/image-upload",
type: "POST",
data : formdata,
processData: false,
contentType: false,
success:function(data){
console.log(data.image);
},
error:console.log('Error'),
});
});
}
One thing i know is laravel need file instance to upload image using laravel storage helpers so check if your upload is file instance or not. Here is a solution if your uploaded file is base64 and you want to change it to file instance How to convert base64 image to UploadedFile Laravel
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));
}
I dynamically generate svg markup on client side and convert it to a data-url for downloading purposes. This procedure works fine and generates a valid svg file.
Besides I have a Java Servlet which takes an uploaded svg file and converts it to pdf. When I take a downloaded svg file from above and upload it through a standard HTML form this Servlet works absolutely fine.
I just want to combine those two parts by sending the generated svg without even saving it before. I already tried to send the data as base64 string like that:
reader.readAsDataURL(blob);
reader.onloadend = function() {
base64data = reader.result;
console.log(base64data );
form['data'].value = base64data;
form.submit();
}
But this doesn't seem to work. Are there any ways of emulating a file upload with JavaScript?
You should use FormData object:
$('form').submit(function(){
/**** creating blob object
.....
****/
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
base64data = reader.result;
var fd = new FormData(this);
fd.append('file', base64data, 'file_data'); // field_data - "Optional" param, it means The filename reported to the server
fd.append('other_field', fieldvalue);
$.ajax({
type: 'POST',
url: '/upload.php',
data: fd,
processData: false,
contentType: false
}).done(function(data) {
console.log(data);
});
}
});
I am able to upload a spreadsheet (.csv or XLS files), but when checking on the file from Parse.com, it is all empty. I am uploading the file from client side code (not using REST). Do you think that is the problem? This works just fine for a simple image/file upload using a similar code, but fails for csv or xls type file.
Here's the code:
$scope.uploadSpFile = function(fileUpload){
var name = fileUpload.name;
var parseFile = new Parse.File(name, fileUpload.spFile);
var serverUrl = 'https://api.parse.com/1/files/' + fileUpload.name;
var mySpreadsheet = new Parse.Object(fileUpload.className);
$.ajax({
type: "POST",
beforeSend: function(request) {
request.setRequestHeader("X-Parse-Application-Id", parse_app_id);
request.setRequestHeader("X-Parse-REST-API-Key", parse_rest_id);
request.setRequestHeader("Content-Type", fileUpload.spFile.type);
},
url: serverUrl,
data: fileUpload.mySpreadsheet,
processData: false,
contentType: false,
success: function(data) {
mySpreadsheet.set({filetitle: data.name});
mySpreadsheet.set({fileurl: data.url});
mySpreadsheet.set({name: name});
mySpreadsheet.set({fileCategory: ''});
mySpreadsheet.set({file: {"name": data.name,"url": data.url,"__type": "File"}});
mySpreadsheet.save();
console.log('file saved!');
},
error: function(data) {
var obj = jQuery.parseJSON(data);
console.log('error: ' + obj.error);
outputMsg = obj.error;
}
});
}
});
when i use a similar code to upload an image, I can access the file on my parse page, but xls or csv files turn out to be empty (actually, in XLS case, an error pops out as the format is corrupted).
Anyone has any idea how to fix this issue?
thanks for the help.
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