Sharepoint AddIn upload .PDF via SP REST API - javascript

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);
});
}

Related

Upload file failed to save in Database

public JsonResult SaveAttachment(string buyerCode)
{
Dictionary<int, CheckSessionData> IDictionary = CheckSessionData.GetSessionValues();
long companyId = (long)IDictionary[1].Id;
long userId = (long)IDictionary[3].Id;
var buyer = DB.Buyers.FirstOrDefault(x => x.Code == buyerCode);
string basePath = "~/Upload/BuyerAttachment/";
string path = Server.MapPath(basePath);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
HttpFileCollectionBase files = Request.Files;
List<string> filePathList = new List<string>();
for (int i = 0; i > files.Count; i++)
{
HttpPostedFileBase file = files[i];
var date = DateTime.Now.ToString().Replace('/', '_');
string FilePath = Path.Combine(path, date.Replace(':', ' ') + file.FileName);
file.SaveAs(FilePath);
filePathList.Add(FilePath);
}
foreach (var item in filePathList)
{
var buyerAttachment = new Buyer_Attachment();
buyerAttachment.BuyerId = buyer.BuyerId;
buyerAttachment.DateOfEntry = DateTime.Now;
buyerAttachment.EntryBy = userId;
buyerAttachment.AttachmentURL = path;
DB.Buyer_Attachment.Add(buyerAttachment);
}
try
{
DB.SaveChanges();
}
catch (Exception)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
return Json(true);
}
}
function SaveAttachment(code) {
var files = $("#CustomerAttachment").get(0).files;
var fileData = new FormData();
for (var i = 0; i < files.length; i++) {
fileData.append("fileInput", files[i]);
}
$.ajax({
type: "POST",
url: "/BuyerSimple/SaveAttachment?buyerCode="+code,
dataType: "json",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function (result, status, xhr) {
filePathList = result;
$('#AttachmentPathList').val(result);
},
error: function (xhr, status, error) {
alert(status);
}
});
}

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();
});
});

can't update json on a github repository by GAS

I'm a very beginner about GAS, and As you can see, my English is not perfect.
I want to upload json file on a github repository by GooleAppsScript.
I can update markdown file, but I cannot do json file.
There is no error on GAS, but when I check the commit log, it says '0 changed files'.
where part should I change the following code?
github repository
function editJson() {
var prop = PropertiesService.getScriptProperties().getProperties();
const date = new Date();
var option = { name: prop.NAME, email: prop.EMAIL };
var github = new GitHubAPI(prop.GITHUB_USERNAME, prop.GITHUB_REPO, prop.GITHUB_TOKEN, option);
var content = ['a', 'b', 'c']
var branch = github.getBranch(prop.GITHUB_BRANCH);
var pTree = github.getTree(branch['commit']['commit']['tree']['sha']);
var blob = github.createBlob(JSON.stringify(content));
var data = {
'tree': pTree['tree'].concat([{
'path': 'json/test.json',
'mode': '100644',
'type': 'blob',
'sha': blob['sha']
}])
};
var tree = github.createTree(data);
var commit = github.createCommit('commit!!', tree['sha'], branch['commit']['sha']);
var result = github.updateReference(prop.GITHUB_BRANCH, commit['sha']);
Logger.log(result);
}
(function(exports) {
var GitHubAPI;
GitHubAPI = (function(){
GitHubAPI.name = 'GitHubAPI';
function GitHubAPI(userid, repo, token, option) {
this.userid = userid;
this.repo = repo;
this.token = token;
this.option = option != null ? option : {};
if(!this.option.tz) this.option.tz = Session.getScriptTimeZone();
this.BASE_URL = 'https://api.github.com/repos/';
this.API_ENDPOINT = "" + this.BASE_URL + this.userid + '/' + this.repo;
}
GitHubAPI.prototype.runREST = function(method, endpoint, data) {
var params;
switch (method) {
case 'GET':
params = { headers : { Authorization: 'token ' + this.token } };
break;
case 'POST':
case 'PATCH':
params = {
headers: {
Authorization: 'token ' + this.token
},
method: method,
contentType: 'application/json',
payload: JSON.stringify(data)
};
break;
default:
throw 'undefined HTTP method: ' + method;
}
var response = UrlFetchApp.fetch(this.API_ENDPOINT + endpoint, params);
return JSON.parse(response);
};
GitHubAPI.prototype.get = function(endpoint){ return this.runREST('GET', endpoint, null); };
GitHubAPI.prototype.post = function(endpoint, data){ return this.runREST('POST', endpoint, data); };
GitHubAPI.prototype.patch = function(endpoint, data){ return this.runREST('PATCH', endpoint, data); };
GitHubAPI.prototype.toISOFormat = function(date, tz) {
return Utilities.formatDate(date, tz, "yyyy-MM-dd'T'HH:mm:ssXXX");
};
GitHubAPI.prototype.getBranch = function(branchName) {
return this.get('/branches/' + branchName);
};
GitHubAPI.prototype.createBlob = function(content) {
return this.post('/git/blobs', { 'content': content, 'encoding': 'utf-8' });
};
GitHubAPI.prototype.createCommit = function(message, treeSha, parentSha) {
var data = {
'message': message,
'author': {
'name': this.option.name,
'email': this.option.email,
'date': this.toISOFormat(new Date(), this.option.tz)
},
'parents': [parentSha],
'tree': treeSha
}
return this.post('/git/commits', data);
};
GitHubAPI.prototype.updateReference = function(branchName, commitSha) {
return this.patch('/git/refs/heads/' + branchName, { 'sha': commitSha });
};
GitHubAPI.prototype.getTree = function(treeSha) {
return this.get('/git/trees/' + treeSha);
};
GitHubAPI.prototype.createTree = function(data) {
return this.post('/git/trees', data);
};
return GitHubAPI;
})();
return exports.GitHubAPI = GitHubAPI;
})(this);

JavaScript - Chaining promises not running in order

I'm developing a small application where user can upload multiple file by a common input file field.
When an user clicks to the "Submit" button, I'm running this code:
function UploadFiles() {
var loadFiles = document.getElementById('selectedFile').files;
for (var i=0; i<=loadFiles.length;i++){
var fileOgg = loadFiles[i];
if (fileOgg!=undefined || fileOgg!=null){
new Promise(function (resolve, reject) { resolve (fileOgg); })
.then(UploadFilesStep)
.then(retrieveMetadata)
.then(changeMetadata)
.then(moveTo)
.then(showSuccess);
}
}
}
This is the UploadFilesStep detail:
var UploadFilesStep = function (fileOgg) {
return new Promise(function(resolve, reject) {
pnp.setup({ headers: { "Cache-Control": "no-cache", }, });
// This is a SharePoint PnP call to file upload
pnp.sp.web.getFolderByServerRelativeUrl("/sites/mysite/Config").files.add(fileOgg.name, fileOgg, true).then(function(result) {
console.log("FileUpload success");
resolve([result, fileOgg]);
});
})
}
The retrieveMetadata code:
var retrieveMetadata = function ([result, fileOgg]) {
return new Promise(function(resolve, reject) {
pnp.setup({ headers: { "Cache-Control": "no-cache", }, });
result.file.listItemAllFields.get().then(function(listItemAllFields) {
resolve([listItemAllFields, fileOgg]);
});
})
}
And this is the changeMetadata promise:
var changeMetadata = function ([listItemAllFields, fileOgg]) {
return new Promise(function(resolve, reject) {
pnp.setup({ headers: { "Cache-Control": "no-cache", }, });
pnp.sp.web.lists.getByTitle("Config").items.getById(listItemAllFields.Id).update({
Number: ""+number+"",
}).then(function(r){
console.log("Properties updated successfully! Go to MoveTo");
resolve(fileOgg);
});
})
}
And finally the MoveTo code:
var moveTo = function (fileOgg) {
return new Promise(function(resolve, reject) {
var nameFile = fileOgg.name;
var timestamp = + new Date();
var fileName = nameFile.substr(0, nameFile.lastIndexOf('.'));
var newFileName = fileName + "-" + timestamp;
var sourceFileUrl = _spPageContextInfo.webServerRelativeUrl+"/Config/"+nameFile+"";
var targetFileUrl = _spPageContextInfo.webServerRelativeUrl+"/Attachments/"+nameFile.replace(fileName, newFileName)+"";
var headers = headers || {};
var method = 'POST';
headers["Accept"] = "application/json;odata=verbose";
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
var endpointUrl = siteurl2 + "/_api/web/GetFileByServerRelativeUrl('" + sourceFileUrl + "')/MoveTo(newurl='" + targetFileUrl + "',flags=1)";
var payload;
$.ajax({
url: endpointUrl,
type: method,
contentType: "application/json;odata=verbose",
data: JSON.stringify(payload),
cache: false,
headers: headers,
async: false,
success: function (data) {
strResults += "";
counterUpload = counterUpload + 1;
resolve();
},
error: function (data) {
strResults += "Error " + JSON.stringify(data, null, 4);;
resolve();
}
});
});
}
From console of my browser I can see that first two promises (UploadFilesStep and retrieveMetadata) are running with the correct order.
Then, I can't see the changeMetadata log, but it seems going forward with the for loop in UploadFiles.
After a while I receive the response from changeMetadata and it often returns a 404 error ("Error making HttpClient request in queryable" linked to pnp js file).
What am i doing wrong?

How to name uploaded chunk using html5?

I have this code:
function upload_by_chunks() {
var chunk_size = 1048576; // 1MB
function slice(start, end) {
if (file.slice) {
return file.slice(start, end);
} else if (file.webkitSlice) {
return file.webkitSlice(start, end);
}
}
var i = 0;
function process(start, end) {
if (start < file.size) {
var chunk = slice(start, end);
chunk.name = file.name;
var formData = new FormData();
formData.append('file', chunk);
formData.append('token', token);
formData.append('path', leash.cwd);
$.ajax({
url: 'lib/upload.php?append=1',
type: 'POST',
success: function(response) {
if (response.error) {
alert(response.error);
}
process(end, end+chunk_size);
},
error: function(jxhr, error, status) {
alert(jxhr.statusText);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
} else {
alert('File "' + file.name + '" uploaded.');
}
}
process(0, chunk_size);
}
I've set the name using chunk.name = file.name; but in php the filename is blob.
$fname = basename($_FILES['file']['name']);
There is an optional third parameter of the method append, which allows you to set a file name for a blob.
formData.append('file', chunk, file.name);

Categories