How to name uploaded chunk using html5? - javascript

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

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

if i using angularjs function excel upload button function how to write my code

I writed code
$scope.updatepricingimport = function(file) {
debugger
if(file == null || file == undefined || file == "")
{
toastr.error("Please Select file");
angular.element("#shipmentdata").modal("show");
return false;
}
$scope.showlodebar = true;
var fd = new FormData();
fd.append("file", file);
return $http
.post(
$localStorage.apiURL +
"/Leaserate/ValidatepricingsUpload?id=" +
$scope.pricing.pricingId,
fd, {
transformRequest: angular.identity,
credentials: "include",
cache: "no-cache",
mode: "cors",
headers: {
"Content-Type": undefined,
},
}
)
.then(function(response) {
debugger
if (response.data.errorUpload == true) {
$scope.items = response.data.uploadError;
$scope.ShowError = true;
angular.element("#shipmentdata").modal("hide");
toastr.error(" Upload Please find the document downloaded for details");
} else {
toastr.success("Shipment Uploaded successfully");
$scope.checktankimport = true;
$scope.getAllPricings();
// $scope.LCTankTypesListLen = $scope.LCTankTypesList.length;
}
// $scope.LCTankTypesList = response.data.lstanktypelist;
// $scope.LCTankTypesListLen = $scope.LCTankTypesList.length;
// $scope.Tanklen = $scope.LCTankTypesList.length;
$scope.showlodebar = false;
// $scope.applyLCTankTypePage(1);
})
.catch(function(response) {
console.log(response);
});
}
Error in my code:

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

Categories