File upload progress Custom page RestAPI SPO - javascript

The code below is working fine to upload files to SPO through RestAPI. No feedback is received on file upload progress. An alert is thrown once the upload is complete.
I would like to have a progress bar to display the upload percentage and reload this upload page while clicking OK to the successful alert message.
Kindly assist.
<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script type="text/javascript">
$(document).ready(function () {
init();
});
function init(){
$("#btnUploadFiles").click(function(){
var files=$("#inputTypeFiles")[0].files;
uploadFiles(files[0]); // uploading singe file
});
}
function uploadFiles (uploadFileObj) {
var fileName = uploadFileObj.name;
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var documentLibrary="TEST";
var folderName = "";
var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/" + documentLibrary + "/" + folderName;
var url = webUrl + "/_api/Web/GetFolderByServerRelativeUrl(#target)/Files/add(overwrite=true, url='" + fileName + "')?$expand=ListItemAllFields&#target='" + targetUrl + "'";
uploadFileToFolder(uploadFileObj, url, function (data) {
var file = data.d;
var updateObject = {
__metadata: {
type: file.ListItemAllFields.__metadata.type
},
departname: $("#departname").val(), //meta data column1
Filename: $("#filename").val(), //meta data column2
ACFTREG: $("#ACFTREG").val(), //meta data column3
Date: $("#datepicker").val() //meta data column4
};
url = webUrl + "/_api/Web/lists/getbytitle('"+documentLibrary+"')/items(" + file.ListItemAllFields.Id + ")";
updateFileMetadata(url, updateObject, file, function (data) {
alert("File uploaded & metadata updation done successfully");
}, function (data) {
alert("File upload done but metadata updating FAILED");
});
}, function (data) {
alert("File uploading and metadata updating FAILED");
});
}
function getFileBuffer(uploadFile) {
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(uploadFile);
return deferred.promise();
}
function uploadFileToFolder(fileObj, url, success, failure) {
var apiUrl = url;
var getFile = getFileBuffer(fileObj);
getFile.done(function (arrayBuffer) {
$.ajax({
url: apiUrl,
type: "POST",
data: arrayBuffer,
processData: false,
async: false,
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
});
}
function updateFileMetadata(apiUrl, updateObject, file, success, failure) {
$.ajax({
url: apiUrl,
type: "POST",
async: false,
data: JSON.stringify(updateObject),
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Content-Type": "application/json;odata=verbose",
"X-Http-Method": "MERGE",
"IF-MATCH": file.ListItemAllFields.__metadata.etag,
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getItems);
function getItems() {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('L%20-%20MDB%20-%20ACFTREG')/items?$Select=Title&$top=2000",
type: "GET",
headers: {
"accept": "application / json;odata = verbose",
},
success: function(data) {
var results = data.d.results;
var options = "";
for(var i = 0; i < results.length; i++){
options = options + "<option value='" + results[i].Title + "'>" + results[i].Title + "</option>";
}
$("#ACFTREG").append(options);
},
error: function(error) {
alert(JSON.stringify(error));
}
});
}
$( function() {$( "#datepicker" ).datepicker(
{
changeMonth: true,
changeYear: true
}
);} );
</script>
Select File:<input type="File" id="inputTypeFiles" /><br />
Departname: <input id="departname" type="textbox"/><br />
Date: <input type="text" id="datepicker" autocomplete="off" name="hidden"><br />
Filename: <input id="filename" type="textbox"/><br />
ACFTREG: <select id="ACFTREG" class="select">
<option selected="selected">Select</option><br />
<input type="button" id="btnUploadFiles" value="Upload"/><br />

Inside the $.ajax({}) function, you can add the xhr setting inside the ajax.
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
// Place upload progress bar visibility code here
}
}, false);
return xhr;
},
type: 'POST',
//add the rest of ajax settings
check this link for ajax documentation
jQuery/ajax
check this link for example on upload progress
jQuery-upload-progress/example

Related

How to get the file uploading progress status in ajax call?

I am uploading the multiple files through ajax, where i need to keep a progress bar. I am able to get the progress complete status only after all the process done, so i need to keep the progress bar showing status during upload.
Here when I clicking the 'btnEditImageSave' button, I am checking whether the existing file is getting delete and uploading in if condition.
In that storing the uploading file and passing it for uploading process in ajax complete function. In it that i have included the progress bar code to show the progress status, but its showing only after the all the process completes.
$('#btnEditImageSave').unbind().click(function (event) {
$('#progressBardiv').css('width', '0');
$('.progressBardiv').text('');
if (uploadedfiles.length > 0 && deleteFiles.length == 0) {
if (editStoredFiles.length > 0) {
var files = new FormData();
for (var i = 0; i < editStoredFiles.length; i++) {
if (editStoredFiles[i].size > 0) {
files.append(editStoredFiles[i].name, editStoredFiles[i]);
}
}
uploadedfiles = [];
files.append('SerialNumber', editSerialNumber);
$.ajax({
type: "POST",
url: productionBaseUrl + '/Home/UploadDockingStationFiles',
data: files,
contentType: false,
processData: false,
async: true,
complete: function () {
uploadedfiles = [];
$('#editfileupload').val();
$.ajax({
type: "POST",
url: cloudServerUrl + "/api/dockstation/updatefiledisplaytimer",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
SerialNumber: $('#ddlEditDockingStationSerialNumber').val(),
FileSpinTimer: $('#txtEditTimer').val(),
IsHDMIUpdate: isHDMIUpdate
}),
/*----My Progress Bar code----*/
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (event) {
if (event.lengthComputable) {
var percentComplete = event.loaded / event.total;
percentComplete = parseInt(percentComplete * 100);
$('#progressBardiv').text(percentComplete + '%');
$('#progressBardiv').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
complete: function () {
$('#loading-popup').hide();
$('#divEditDockingStationImages').dialog("close");
$.popup('<pre>Message</pre>', "Image Configuration Updated Successfully.", 'OK');
return false;
}
});
}
});
}
}
else {
$('#loading-popup').hide();
$.popup('<pre>Message</pre>', "Please Select a File.", 'OK');
return false;
}
}
<div class="progress">
<div id="progressBardiv" class="progress-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" style="">
<span class="sr-only"></span>
</div>
</div>
For those in 2022 still looking how to measure an XHR upload operation progress, there's an API called ProgressEvent (https://developer.mozilla.org/en-US/docs/Web/API/ProgressEvent) with broad support of major browsers. No need to use custom plugins.
Also, a detailed post with examples on how to use this can be found here: https://medium.com/swlh/uploading-files-with-progress-monitoring-in-vanillajs-angular-and-vuejs-625e2491821
You can use plUpload plugin to upload files..
Follow this link:https://www.plupload.com/docs
it has its own event for progressbar...
See the sample code below...
var uploader = new plupload.Uploader({
runtimes: 'html5,flash,silverlight,html4',
browse_button: 'pickfiles', // you can pass in id...
container: document.getElementById('container'), // ... or DOM Element itself
url: "//",
filters: {
max_file_size: '500mb',
mime_types: [
{ title: "PDF files", extensions: "pdf" }
]
},
flash_swf_url: '/plupload/js/Moxie.swf', // Flash settings
silverlight_xap_url: '/plupload/js/Moxie.xap', // Silverlight settings
init: {
PostInit: function () {
// whereas filelist is the divid which contains uploaded file names....
document.getElementById('filelist').innerHTML = '';
uploader.start();
},
FilesAdded: function (up, files) {
plupload.each(files, function (file) {
document.getElementById('filelist').innerHTML +=
'<div id ="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) +
') <b></b> Remove</div>' +
'<div class="progressbar" id ="progressBar_' + file.id + '"> <div class="mybar" id="myBar' + file.id + '"></div></div>';
});
},
UploadProgress: function (up, file) {
var $progressId = $("#filelist div#progressBar_" + file.id + " div.mybar");
$progressId.css('width', file.percent + '%');
//To Remove 'Remove Link' while file is in uploading state.
$("#filelist div#" + file.id).find('a.remove').remove();
document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
},
FileUploaded: function (up, file, ServerResponse) {
var response = JSON.parse(ServerResponse.response);
},
UploadComplete: function (up, file) {
},
Error: function (up, err) {
document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
}
}
});
uploader.init();
I have used in my project have a look on snapshot below,
if (deleteFiles.length > 0 && uploadedfiles.length > 0) {
$.ajax({
type: "POST",
url: productionBaseUrl + "/Home/DeleteDockingStationFiles",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
data: JSON.stringify({
serialNumber: editSerialNumber,
files: deleteFiles
}),
complete: function () {
deleteFiles = [];
if (editStoredFiles.length > 0) {
var files = new FormData();
for (var i = 0; i < editStoredFiles.length; i++) {
if (editStoredFiles[i].size > 0) {
files.append(editStoredFiles[i].name, editStoredFiles[i]);
}
}
uploadedfiles = [];
files.append('SerialNumber', editSerialNumber);
$.ajax({
type: "POST",
url: productionBaseUrl + '/Home/UploadDockingStationFiles',
data: files,
contentType: false,
processData: false,
async: true,
xhr: function (data) {
var xhr = new window.XMLHttpRequest(data);
xhr.upload.addEventListener("progress", function (event) {
if (event.lengthComputable) {
var percentComplete = event.loaded / event.total;
percentComplete = parseInt(percentComplete * 100);
$('#progressBardiv').text(percentComplete + '%');
$('#progressBardiv').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
beforeSend: function () {
uploadedfiles = [];
$('#editfileupload').val();
$.ajax({
type: "POST",
url: cloudServerUrl + "/api/dockstation/updatefiledisplaytimer",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
SerialNumber: $('#ddlEditDockingStationSerialNumber').val(),
FileSpinTimer: $('#txtEditTimer').val(),
IsHDMIUpdate: isHDMIUpdate
}),
complete: function () {
$('#loading-popup').hide();
$('#divEditDockingStationImages').dialog("close");
$.popup('<pre>Message</pre>', "Image Configuration Updated Successfully.", 'OK');
return false;
}
});
}
});
}
}
});
}

Set field Originator Signature to Current User

Good day, I have a SharePoint form the has a Originator Completed Dropdown with Yes or No as options. If the dropdown is yes, I would like to use JavaScript to set the OriginatorSignature (Text Field) to the loginName or current user. Can someone assist with this function?
<script src="/SiteAssets/jquery-3.2.1.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
GetUserLogin();
});
var userid = _spPageContextInfo.userId;
function GetUserLogin() {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
url : requestUri,
contentType : "application/json;odata=verbose",
headers : requestHeaders,
success : QuerySuccess,
error : QueryError
});
}
function QuerySuccess(data, request){
var loginName = data.d.LoginName.split('|')[1];
$("input[title='Originator Signature']").val(loginName);
}
function QueryError(error) {
alert(error);
}
</script>
The following code for your reference.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
if($("select[title='Originator Completed Dropdown']").val()=="Yes"){
GetUserLogin();
}
$("select[title='Originator Completed Dropdown']").change(function(){
if($(this).val()=="Yes"){
GetUserLogin();
}else{
$("input[title='Originator Signature']").val("");
}
});
});
function GetUserLogin(){
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + _spPageContextInfo.userId + ")",
type: "GET",
headers: {
"Accept": "application/json;odata=verbose",
},
success: function (data) {
var loginName = data.d.LoginName;
if(loginName.indexOf("|")!=-1){
loginName = loginName.split('|')[1];
}
$("input[title='Originator Signature']").val(loginName);
},
error: function (data) {
//alert("Error");
}
});
}
</script>

Profile image not loading from delve on Sharepoint

I'm trying to get the profile image from delve and display it on a Sharepoint page using Javascript,the problem i'm getting is that the image isn't loading always
var profileimage="https://eur.delve.office.com/mt/v3/people/profileimage?userId="+userInfo["SPS-ClaimID"]+"&size=L";
If you want to display the profile image, we can use the url as below.
var profileimage="/_layouts/15/userphoto.aspx?size=L&username=lz#tenant.onmicrosoft.com";
Example code:
<script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/siteusers?$select=Id,Title,Email";
$.ajax({
url: url,
method: "GET",
async: false,
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var items=data.d.results;
var options="<option>--select a user--</option>";
for(var i=0;i<items.length;i++){
if(items[i].Email!=""){
options+="<option value='"+items[i].Email+"'>"+items[i].Title+"</option>";
}
}
$("#SiteUsers").html(options);
},
error: function (data) {
}
});
$("#SiteUsers").change(function(){
var html="";
if($(this).val()!=null&&$(this).val()!=""){
html+="<img src='/_layouts/15/userphoto.aspx?size=L&username=" + $(this).val() + "'/>";
}
if($(this).children(':selected').text()!=""){
html+="<p><span>Name:"+ $(this).children(':selected').text()+"</span></p>";
}
$("#UserInfomation").html(html);
});
});
</script>
<select id="SiteUsers"><option>--select a user--</option></select>
<div id="UserInfomation"></div>

Using variables from one script in another script in a string. Jquery/Javascript

Why does the below not work when run. I am trying to declare a variable in Script 1 I thought defining the variable outside would allow it to be global. I will say this is for a chrome application, I have the necessary permission in my manifest and I have the correct script for Jquery in my HTML.
var userName;`
and then use that in script 2 `
var text = 'Hello' + userName + 'This is a test'`
Full Code
Script 1
var userName;
var userEmail;
var userTeamName;
function currentUrl() {
return new Promise(function (resolve) {
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
resolve(tabs[0].url)
})
})
}
function userIdfromUrl(url) {
var parts = url.split('/')
return parts[parts.length - 1]
}
var authorizationToken = "xxxxxxxxxxxxxxxxxxxxxxx";
function myapiRequest(endpoint, options) {
$.ajax($.extend({}, {
type: 'GET',
dataType: "json",
success: function(data) {
$('.Name').html(data.user.name);
$('.Email').html(data.user.email);
$('.Address').html(data.user.teams[0].name);
},
url: "https://api.myapi.com/" + endpoint,
headers: {
"Authorization": "Token token=" + authorizationToken,
"Accept": "application/vnd.myapi+json;version=2"
}
},
options));
}
currentUrl()
.then(function (url) {
return userIdfromUrl(url)
})
.then(function (userId) {
return myapiRequest('users/' + userId + '?include%5B%5D=contact_methods&include%5B%5D=teams')
})
.then(function (data) {
console.log(data.user.name)
console.log(data.user.email)
console.log(data.user.teams[0].name)
jsonData = data.user.name;
of the function
})
.then(function(data) {
userName = data.user.name;
userEmail = data.user.email;
userTeamName = data.user.teams[0].name;
})
Script 2
$(document).ready(function() {
$('#contact-submit').on('click', function(e) {
e.preventDefault();
var btn = $(e.target);
btn.attr("disabled", "disabled"); // disable button
var url = 'https://hooks.slack.com/services/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
var text = 'Hello' + userName + 'This is a test'
$.ajax({
data: 'payload=' + JSON.stringify({
"text": text
}),
dataType: 'json',
processData: false,
type: 'POST',
url: url
});
});
});

how can i use post and files with ajax?

i'd like to know how can i use $_POST and $_FILES using ajax, i'm trying to upload an image and insert a value on my database with post.
i've tried but it doesn't work.
index.html
<div class="form-group">
<label> img </label>
<input type="file" name="img" id="img" />
<input type='hidden' id='value' value='<?=$_GET["p"]?>' />
</div>
ajax.js
$(document).ready(function() {
$('#upload').click(function() {
var value = $('#value').val();
var img = $('#img').val();
var string= 'value=' + value + '&img=' + img;
$.ajax({
type: "POST",
url: "ajax.php",
data: string,
dataType: "json",
success: function(data) {
var success = data['success'];
if (success == true) {
console.log('success');
} else {
console.log('error');
}
}
});
return false;
});
});
ajax.php
<?php
if(isset($_POST["value"]) && isset($_FILES["img"])) {
echo json_encode(array("success" => true));
} else {
echo json_encode(array("success" => false));
}
?>
The best approach is convert image to base64 first. This conversion is done in the change listener.
var files = [];
$("input[type=file]").change(function(event) {
$.each(event.target.files, function(index, file) {
var reader = new FileReader();
reader.onload = function(event) {
object = {};
object.filename = file.name;
object.data = event.target.result;
files.push(object);
};
reader.readAsDataURL(file);
});
});
$("form").submit(function(form) {
$.each(files, function(index, file) {
$.ajax({url: "/ajax-upload",
type: 'POST',
data: {filename: file.filename, data: file.data},
success: function(data, status, xhr) {}
});
});
files = [];
form.preventDefault();
});

Categories