How .doc file print in google chrome using js? - javascript

i have a url for doc file
how pirnt this on any browser
function printdoc(id) {
$.ajax({
type: "POST",
url: "/Document/GetDocIdByDocumentUrl",
data: { id: id },
success: function (url) {
debugger
let Filename = url.substr(url.lastIndexOf("/") + 1)
if (IsDoc) {
let new_window = window.open(`https://docs.google.com/viewerng/viewer?url=${url}`, '', 'height=500, width=500');
let doc = document.createElement("iframe");
doc.style.height = "100%";
doc.style.width = "100%";
doc.src = "https://docs.google.com/gview?url=" + url + "&embedded=true";
new_window.document.write(doc.outerHTML);
setTimeout(() => {
new_window.print();
new_window.close();
}, 2000);
}
},
error: function (err) {
console.log(err);
}
});
}
i have try this code , but file quality not good and not full size
any solution

Related

How do I confirm a 100% Redirect through Javascript by using async await

I am trying to redirect to another server call but unfortunately browser sometimes redirect or sometime just refresh the current page.
Redirect is in getCheckOutOfHrs async function and I tried all three options
1). window.location = myurl;
2). window.location.href = myurl;
3). window.location.assing(myurl);
4). window.location.replace(myurl);
Nothing is 100% a working solution in my case. sometimes browser redirects and sometimes not.
I don't know why browser is doing this. see my tried code is below.
I am trying to use async function.
$('#btn-search-car').click(function(e) {
searchCar(e)
});
function searchCar(e) {
try {
//debugger;
e.preventDefault();
var obj = {
Branch: lStrLocNam.trim(),
PickupLocId: lIntPickupLocId,
FranchiseId: lIntFranchiseId,
SubofficeId: lIntSubofficeId,
StartDate: dtStart /*startDate*/ ,
StartTime: startTime,
EndDate: dtEnd /*endDate*/ ,
EndTime: endTime,
VehicleType: selectedVehType,
VehicleCategoryId: carCat,
IsNewSearch: true
};
saveElement('SelectedParamInSearch', obj);
let apiUrl = REACT_APP_CheckOutOfHours;
getCheckOutOfHrs(obj);
} catch (err) {
//hideProgress();
}
};
const getCheckOutOfHrs = async(obj) => {
let abortController = new AbortController();
let lattitude = 0;
let longitude = 0;
let resultPages = [];
let apiUrl = REACT_APP_CheckOutOfHours;
const settings = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(obj),
signal: abortController.signal
};
const responseDetail = await fetch(apiUrl, settings);
//abortController.abort();
if (responseDetail && !responseDetail.ok) {
resultPages = [];
} else {
resultPages = await responseDetail.json();
}
try {
let OutOfHours = resultPages; //? JSON.parse(resultPages):'';
//debugger;
debugger;
if (OutOfHours) {
saveElement('OutOfHoursParam', OutOfHours);
//OutOfHours = OutOfHours.replace('"', '').replace('"', '');
if (OutOfHours.length != 0 && OutOfHours.item2 && OutOfHours.item2.indexOf("£") > 0) {
//window.location = "/Home/FindBranch/?franchiseId=" + obj.FranchiseId;
let redirectLocalUrl = "/Home/FindBranch/?franchiseId=" + obj.FranchiseId;
window.location.replace(redirectLocalUrl);
// window.location.href = redirectLocalUrl;
// windowtruelocation.assign(redirectLocalUrl);
return false;
/* $.ajax({
url: "/Home/FindBranch",
data: obj,
success: function (data) {
window.location.href = "/Home/FindBranch";
},
dataType: "html",
type: "POST",
cache: false,
error: function () {
}
}); */
} else if (OutOfHours.length != 0 && OutOfHours.item2 && OutOfHours.item2.indexOf("£") < 0) {
//OutOfHours = OutOfHours.replace("\\", "'").replace("\\", "");
alert(OutOfHours.item2);
return false;
} else {
//FindBranch
//window.location = "/Home/FindBranch/?franchiseId=" + obj.FranchiseId;
let redirectLocalUrl = "/Home/FindBranch/?franchiseId=" + obj.FranchiseId;
window.location.replace(redirectLocalUrl);
// window.location.href = redirectLocalUrl;
// window.location.assign(redirectLocalUrl);
return true;
/* $.ajax({
url: "/Home/FindBranch",
data: obj,
success: function (data) {
// debugger;
window.location.href = "/Home/FindBranch";
//hideProgress();
},
dataType: "html",
type: "POST",
cache: false,
error: function () {
// hideProgress();
}
}); */
}
}
} catch (error) {
debugger;
}
};
Help is appreciated.

Saving File to Share Point - vue.js

Trying to upload file from web application to SharePoint directory. Upon successful upload, only the filename is saved to the database. A SharePoint link is hard coded in the frontend to view the file uploaded.
Problem encountered: Sometimes the upload fails with an error message "session was expired.. Please clear the local storage." Clearing cache does not help.
importFiles: retrieves an array of all files from the database.
saveFile: adds the last successfully file name to the end of the array
clearCache: clears the input type [rename field]
var savingFile = function () {
importFiles(() => saveFile(() => clearCache(() => {
$('#modal').modal('hide');
init();
})));
Following is to upload the selected file to the SharePoint directory.
upon successfully upload, () => { savingFile(); }); is called to save the file.
upload_SP() {
if (app.selectedFile.length == 0) {
alert("please select file to upload..");
app.isLoading = false;
return;
}
_.each(app.selectedFile, function (item, index) {
var blob = item.slice(0, item.size, 'image/jpg');
app.finalFile = new File([blob], app.renameFile[index] + '.jpeg', { type: 'image/jpg' });
});
var formData = new FormData();
_.each(app.finalFile, function (file, index) {
formData.append('file-' + index, file);
});
app.sp_action(app.parentId, app.folderId, app.finalFile.name, app.finalFile,
() => { savingFile(); });
}
},
Following method takes the arguments required to upload the file to the SP.
sp_action(parentId, folderId, fileName, data, callback = null) {
$.fileUploadSP(parentId, folderId, fileName, data, function (response) {
app.isSuccessful = response.isSuccessful;
if (response == "success") {
alert("Successfully Uploaded..");
app.messageDismissCountDown = 3;
if (callback) {
callback(response);
}else {
location.reload();
}
}
else {
clearCache(() => { });
app.message = response.message;
app.isLoading = false;
window.scrollTo(0, 0);
}
});
},
Following is AJAX call made to upload the file to the SharePoint.
window.$.getPathSP = function (parentId, forlderId, fileName) {
var origin = "https://graph.microsoft.com/v1.0/drives/" + parentId + "/items/" + forlderId +
":/" + fileName + ":/content"
return origin;
};
window.$.fileUploadSP = function (parentId, forlderId, fileName, data, callback) {
$.ajax({
type: 'PUT',
url: $.getPathSP(parentId, forlderId, fileName),
headers: graphHeader,
data: data,
contentType: false,
processData: false,
async: true,
crossDomain: true,
cache: false,
success: function (response) {
success(response, function () {
if (callback) {
callback("success");
}
});
},
failure: function (response) {
alert("failed")
failure(response, "fail");
},
error: function (response) {
alert("session was expired.. Please clear the local storage.")
error(response, callback);
}
});
};

How to set parents folder name and get the uploaded image id for Google Drive Api javascript

I have implemented this by following this tutorial and it's working perfectly. After successful authentication the image is uploading on my Google Drive perfectly. But now I want to know
how can I add parent's folder name directory (parent/folderOne/folderTwo) for my uploaded image?
And I also need the fileID for newly uploaded image.
In java script I can do that in
const fileMetadata = {
'name': 'any_file_name',
parents: ['1xxxXj_sdsdsdsd0Rw6qDf0jLukG6eEUl']
};
But here I don't have any knowledge on ajax, so any help would be highly appreciated.
Thanks!
This is the code for uploading to Google Drive:
$(document).ready(function() {
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
const redirect_uri = "http://localhost/googleDriveUpload/upload.html" // replace with your redirect_uri;
const client_secret = "***********"; // replace with your client secret
const scope = "https://www.googleapis.com/auth/drive";
var access_token= "";
var client_id = "********************"// replace it with your client id;
$.ajax({
type: 'POST',
url: "https://www.googleapis.com/oauth2/v4/token",
data: {code:code
,redirect_uri:redirect_uri,
client_secret:client_secret,
client_id:client_id,
scope:scope,
grant_type:"authorization_code"},
dataType: "json",
success: function(resultData) {
localStorage.setItem("accessToken",resultData.access_token);
localStorage.setItem("refreshToken",resultData.refreshToken);
localStorage.setItem("expires_in",resultData.expires_in);
window.history.pushState({}, document.title, "/GitLoginApp/" + "upload.html");
}
});
function stripQueryStringAndHashFromPath(url) {
return url.split("?")[0].split("#")[0];
}
var Upload = function (file) {
this.file = file;
};
Upload.prototype.getType = function() {
localStorage.setItem("type",this.file.type);
return this.file.type;
};
Upload.prototype.getSize = function() {
localStorage.setItem("size",this.file.size);
return this.file.size;
};
Upload.prototype.getName = function() {
return this.file.name;
};
Upload.prototype.doUpload = function () {
var that = this;
var formData = new FormData();
// add assoc key values, this will be posts values
formData.append("file", this.file, this.getName());
formData.append("upload_file", true);
$.ajax({
type: "POST",
beforeSend: function(request) {
request.setRequestHeader("Authorization", "Bearer" + " " + localStorage.getItem("accessToken"));
},
url: "https://www.googleapis.com/upload/drive/v2/files",
data:{
uploadType:"media"
},
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', that.progressHandling, false);
}
return myXhr;
},
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
},
async: true,
data: formData,
cache: false,
contentType: false,
processData: false,
timeout: 60000
});
};
Upload.prototype.progressHandling = function (event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
var progress_bar_id = "#progress-wrp";
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
// update progressbars classes so it fits your code
$(progress_bar_id + " .progress-bar").css("width", +percent + "%");
$(progress_bar_id + " .status").text(percent + "%");
};
$("#upload").on("click", function (e) {
var file = $("#files")[0].files[0];
var upload = new Upload(file);
// maby check size or type here with upload.getSize() and upload.getType()
// execute upload
upload.doUpload();
});
});

Sharepoint AddIn upload .PDF via SP REST API

i have a function, which is uploading files to list item. Everything is working for .png, but when i'm trying to upload .pdf i have error net::ERR_CONNECTION_RESET
Screen of error object:
My code:
function uploadFile(listName, itemId, fileName, file) {
uploadFileSP(listName, itemId, fileName, file)
.then(function (files) {
//success
}, function (sender, args) {
alert('error: ' + args.get_message());
});
}
function getFileBuffer(file) {
var deferred = $.Deferred();
var reader = new FileReader();
reader.onload = function (e) {
deferred.resolve(e.target.result);
}
reader.onerror = function (e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(file);
return deferred.promise();
}
function uploadFileSP(listName, id, fileName, file) {
var deferred = $.Deferred();
getFileBuffer(file)
.then(function (buffer) {
var bytes = new Uint8Array(buffer);
var content = new SP.Base64EncodedByteArray();
var binary = '';
for (var b = 0; b < bytes.length; b++) {
binary += String.fromCharCode(bytes[b]);
}
console.log(binary);
executor.executeAsync({
url: appweburl + "/_api/web/lists/getbytitle('" + listName + "')/items(" + id + ")/AttachmentFiles/add(FileName='" + file.name + "')",
method: "POST",
binaryStringRequestBody: true,
body: binary,
success: function (data) { alert('Pomyślnie dodano fakturę!'); window.location.replace("http://sharepoint-dev.ampliapps.com/FakturyBPNT-SharePoint-Hosted/Lists/Faktury/AllItems.aspx");},
error: function (err) { alert('Wystąpił błąd podczas wprowadzania faktury.'); console.log(err); },
state: "Update"
})
}, function (error) { deferred.reject(error); });
return deferred.promise();
}
As i said earlier, it works for .png for example.
This is what you need
function uploadDocument(contents, targetPath, successHandler, failedHandler) {
var fileName = getFilenameFromUrl(targetPath);
var fileNameEvidence = fileName;
var folderName = getPathFromUrl(targetPath);
var hostWebUrl = '';
var appWebUrl = '';
hostWebUrl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
appWebUrl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));
$.getScript(hostWebUrl + "/_layouts/15/SP.RequestExecutor.js", function () {
console.log("into upload Api Document");
var byteArray = new Uint8Array(atob(contents).split("").map(function (c) {
return c.charCodeAt(0);
}));
var fileData = '';
for (var i = 0; i < byteArray.byteLength; i++) {
fileData += String.fromCharCode(byteArray[i]);
}
var reqDocExecutor = new SP.RequestExecutor(appWebUrl);
var _url = '';
var contentType = "application/pdf;odata=verbose";
var dotLocation = fileName.lastIndexOf('.');
var extensionFile = fileName.substr(dotLocation);
var info;
_url = String.format("{0}/_api/sp.appcontextsite(#target)/web/GetFolderByServerRelativeUrl('{1}')/files" + "/add(overwrite=true, url='{2}')?#target='{3}'", appWebUrl, folderName, fileName, hostWebUrl);
info = {
url: _url,
method: "POST",
headers: {
"Accept": "application/pdf; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
contentType: contentType,
processData: false,
binaryStringRequestBody: true,
body: fileData,
success: function (x, y, z) {
successHandler();
},
error: function (x, y, z) {
console.log('failed to upload document');
failedHandler();
}
};
reqDocExecutor.executeAsync(info);
});
}

Using a variable after it was changed by another function - getting undefined

I want to get the image path after the execution of the uploadFiles function. This way, I will have the value assigned to self.ProjectImagePath. But it is not working, I think it executes right after the function call. Anyone can help ?
self.submitProject = function(file) {
console.log("Submit Project \n");
uploadFiles.apply(this, arguments);
console.log(self.ProjectImagePath); ///ERROR HERE!!!! (UNDEFINED)
var data = JSON.stringify({
name: self.ProjectName,
room: self.room,
managers: self.Managers,
members: self.ProjectMembers,
image: self.ProjectImagePath
});
//console.log(data);
$http.post('/rooms/' + self.room + '/project', data).success(function(data) {
//$window.location.href = "/";
});
}
function uploadFiles(file) {
file.upload = Upload.upload({
url: 'projectImages/upload',
data: {
file: file
}
});
file.upload.then(function(response) {
$timeout(function() {
file.result = response.data;
self.ProjectImagePath = file.result;
});
}, function(response) {
if (response.status > 0)
self.errorMsg = response.status + ': ' + response.data;
});
}
After execution, the image is uploaded to the server but I cant get its path.
Im using AngularJS
You were having issues with calling code before the promise (asynchronous action) was finished.
This should do what you need:
self.submitProject = function(file) {
console.log("Submit Project");
function handleSuccess(response) {
self.ProjectImagePath = file.result = response.data;
// Should work correctly.
console.log(self.ProjectImage);
var data = JSON.stringify({
name: self.ProjectName,
room: self.room,
managers: self.Managers,
members: self.ProjectMembers,
image: self.ProjectImagePath
});
$http.post('/rooms/' + self.room + '/project', data).success(function(data) {
//$window.location.href = "/";
});
}
function handleError(response) {
if (response.status > 0)
self.errorMsg = response.status + ': ' + response.data;
}
uploadFiles(file, handleSuccess, handleError);
};
function uploadFiles(file, successCallback, errorCallback) {
file.upload = Upload.upload({
url: 'projectImages/upload',
data: {
file: file
}
});
file.upload.then(successCallback, errorCallback);
}

Categories