I create a simple website for Uploading files on Google Drive using Google Drive Api.
This is My Code :
$.ajax({
type: "POST",
beforeSend: function(request) {
request.setRequestHeader("Authorization", "Bearer" + " " + localStorage.getItem("accessToken"));
},
url: "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart&fields=webViewLink",
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();
});
});
Everything is Oky, But I just want to get the public URL of The files 😠I just want to show the public url after file uploaded. Help Me Please
after upload the file and getting the fileId:
async function generatePublicUrl(fileId) {
try {
await drive.permissions.create({
fileId: fileId,
requestBody: {
role: "reader",
type: "anyone",
},
});
const result = await drive.files.get({
fileId: fileId,
fields: "webViewLink, webContentLink",
});
return result;
} catch (err) {
console.log(err);
}
}
and after doing that you just put your fileId in the format:
https://drive.google.com/file/d/"yourfileId"/preview
The Google Drive api does not have a method for creating the sharable link.
You will need to manually go to the Google drive website and create your sharable link there and store it in your system.
Related
I’m new to tus and I’m using tus-js-client. I’m following the example in this link https://github.com/tus/tus-js-client/blob/master/docs/usage.md#example-upload-to-vimeo.
I was able to successfully upload a video on Vimeo but I would like to set the title/name and description in advance. And also the optional onSuccess function is not returning anything. I would like to get the video details that I’ve uploaded successfully like the clipid.
Are these things something possible to do on tus-js-client? Below is my code for reference.
function UploadVideoTusJs(uploadUrl, videoFile) {
var upload = new tus.Upload(videoFile.files[0], {
uploadUrl: uploadUrl,
metadata: {
name: videoFile.files[0].name, // not working
description: "Test", // not working
},
onError: function (error) {
console.log("Failed because: " + error);
},
onProgress: function (bytesUploaded, bytesTotal) {
var percentage = (bytesUploaded / bytesTotal * 100).toFixed(2)
console.log(bytesUploaded, bytesTotal, percentage + "%")
},
onSuccess: function (data) {
console.log(data); //returns undefined
console.log("Download %s from %s", upload.file.name, upload.url);
},
onAfterResponse: function (req, res) {
var url = req.getURL()
var value = res.getHeader("X-My-Header")
console.log(`Request for ${url} responded with ${value}`)
}
});
// Start the upload by default
upload.start();
}
-- Dan
Vimeo's implementation of tus is a bit different as the "creation" step is done using the Vimeo API, not using tus. If you want to provide metadata like name or description, that should be provided with the initial API request, which should look something like this:
var settings = {
"url": "https://api.vimeo.com/me/videos",
"method": "POST",
"timeout": 0,
"headers": {
"Accept": "application/vnd.vimeo.*+json;version=3.4",
"Content-Type": "application/json",
"Authorization": "Bearer TOKEN"
},
"data": JSON.stringify({"upload":{"approach":"tus","size":666666666},"name":"name","description":"description"}),
};
$.ajax(settings).done(function (response) {
console.log(response);
});
Hope this points you in the right direction!
Hi Im trying to upload a 2 file or more, my problem is my progress bar will say 100% because of the small file being uploaded first, then its going back to the percent of the large file.. My question is how can I have a same progress if i have many files being uploaded?
for (var i = 0, f; f = files.files[i]; i++) {
$.ajax({
xhr: function(){
//upload Progress
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//update progressbar
$('.bar').width(percent + '%');
}, true);
}
return xhr;
},
url: 'https://content.dropboxapi.com/2/files/upload',
type: 'post',
data: f,
processData: false,
contentType: 'application/octet-stream',
headers: {
"Authorization": "Bearer ACCESS TOKEN",
"Dropbox-API-Arg": '{"path": "/'+f.name+'", "mode": "add","autorename": true,"mute": false}'
},
success: function (data) {
console.log(data);
app.alert.show('success-message', {
level: 'success',
messages: 'your file has been upload to Dropbox',
autoClose: true
});
},
error: function (data) {
console.log(data);
}
})
}
I think you should store progress of each file in different variable (or maybe array of variables) and write function, that will update progressbar width when this vars are changed.
This app is an image uploading tool that uploads images directly from client browser to Amazon S3 using Plupload. So far, everything is working good except this issue.
I've this code forBeforeUpload event.
init: {
BeforeUpload: function (up, file) {
$.ajax({
url: '/ServerTime.ashx',
dataType: 'text',
data: { format: "yyyy-MM-dd_HH.mm.ss.fffffff" },
type: 'POST',
cache: false
}).done(function (data) {
console.log("Before setting ImageName: " + data);
imageName = data + ".JPG";
console.log("After setting ImageName: " + imageName);
up.settings.multipart_params = {
'key': key,
'Filename': imageName,
'acl': 'public-read',
'success_action_status': '201',
'AWSAccessKeyId': accessKey,
'policy': policyDocument,
'signature': policySignature
};
});
}
}
However, I've this error when try to upload a file:
HTTP Error. Upload URL might be wrong or doesn't exist.
On Console, it is printing the expected result as follows:
Before setting ImageName: 2014-04-04_13.33.45.1155072
After setting ImageName: 2014-04-04_13.33.45.1155072.JPG
I guess there is something wrong maybe because I'm using AJAX to get time from server. On the other hand, trying the following code is working without any issue.
init: {
BeforeUpload: function (up, file) {
up.settings.multipart_params = {
'key': "This_Is_Folder_Name/This_Is_File_Name.JPG",
'Filename': "This_Is_File_Name.JPG",
'acl': 'public-read',
'success_action_status': '201',
'AWSAccessKeyId': accessKey,
'policy': policyDocument,
'signature': policySignature
};
}
}
Notice that, this time I'm using static names for Filename and key, and there is no AJAX either
I really need help with this issue. Please suggest me. What I'm doing wrong with using AJAX to get server time and use it as file name?
Thanks.
You might be able to override some of their code by doing the following:
init: {
BeforeUpload: function (up, file) {
$.ajax({
url: '/ServerTime.ashx',
dataType: 'text',
data: { format: "yyyy-MM-dd_HH.mm.ss.fffffff" },
type: 'POST',
cache: false
}).done(function (data) {
console.log("Before setting ImageName: " + data);
imageName = data + ".JPG";
console.log("After setting ImageName: " + imageName);
up.settings.multipart_params = {
'key': key,
'Filename': imageName,
'acl': 'public-read',
'success_action_status': '201',
'AWSAccessKeyId': accessKey,
'policy': policyDocument,
'signature': policySignature
};
file.status = plupload.UPLOADING;
up.trigger("UploadFile", file);
});
return false;
}
}
This would cancel their trigger, so you would have to trigger it yourself. Please note, I have not tested this.
EDIT: I'm not sure if up and file are out of scope though...
If you look in the Plupload source code you'll see this:
// Private methods
function uploadNext() {
var file, count = 0, i;
if (this.state == plupload.STARTED) {
// Find first QUEUED file
for (i = 0; i < files.length; i++) {
if (!file && files[i].status == plupload.QUEUED) {
file = files[i];
if (this.trigger("BeforeUpload", file)) {
file.status = plupload.UPLOADING;
this.trigger("UploadFile", file);
}
} else {
count++;
}
}
// All files are DONE or FAILED
if (count == files.length) {
if (this.state !== plupload.STOPPED) {
this.state = plupload.STOPPED;
this.trigger("StateChanged");
}
this.trigger("UploadComplete", files);
}
}
}
The line that says if (this.trigger("BeforeUpload", file)) { will determine whether the return of the trigger call is truthy or falsy. If truthy, it will next trigger "UploadFile". What that means is that the uploading of the file does not wait for asynchronous code to execute in your BeforeUpload function. As soon as that function returns, the upload can begin. Any async ajax call you make inside your BeforeUpload function will resolve after "UploadFile" is triggered.
window.addEventListener("DOMContentLoaded", function() {
// Grab elements, create settings, etc.
var canvas = document.getElementById("uploader-box"),
context = canvas.getContext("2d"),
video = document.getElementById("video"),
videoObj = { "video": true },
errBack = function(error) {
console.log("Video capture error: ", error.code);
};
);
dataURL = canvas.toDataURL("image/png");
dataURL = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
$('#some_text_area_id').val(dataURL); // set the response in text area
// jQuery('#web_image').value(image);
jQuery.ajax({
url: "/my_controller/myaction",
type: "POST",
dataType: 'jsonp',
data: 'image_data='+dataURL,
cache: false,
beforeSend:function(){
},
success: function (response_data) {
},
error: function(response_data) {
}
});
In controller file i have written
data = params[:image_data]
file_obj=File.open("#{Rails.root}/public/images/test.png","wb") do |file|
file.write(Base64.decode64(params[:image_data]))
It gives
Errno::EACCES (Permission denied - test.png):
This error please some one help me. If any another way to save canvas data in ruby please tell me
Thanks,
I have this following snippet for uploading files via Ajax post (using Knockout js library)
ko.bindingHandlers.fileUpload = {
init: function (element, valueAccessor) {
$(element).after('<div class="progress"><div class="bar"></div><div class="percent">0%</div></div><div class="progressError"></div>');
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var options = ko.utils.unwrapObservable(valueAccessor()),
property = ko.utils.unwrapObservable(options.property),
url = ko.utils.unwrapObservable(options.url);
if (property && url) {
$(element).change(function () {
if (element.files.length) {
var $this = $(this),
fileName = $this.val();
alert(fileName);
// this uses jquery.form.js plugin
$(element.form).ajaxSubmit({
url: url, //WEB API URL
type: "POST",
dataType: "text", //I want to upload .doc / excell files
headers: { "Content-Disposition": "attachment; filename=" + fileName },
beforeSubmit: function () {
$(".progress").show();
$(".progressError").hide();
$(".bar").width("0%")
$(".percent").html("0%");
},
uploadProgress: function (event, position, total, percentComplete) {
var percentVal = percentComplete + "%";
$(".bar").width(percentVal)
$(".percent").html(percentVal);
},
success: function (data) {
$(".progress").hide();
$(".progressError").hide();
// set viewModel property to filename
bindingContext.$data[property](data);
},
error: function (jqXHR, textStatus, errorThrown) {
$(".progress").hide();
$("div.progressError").html(jqXHR.responseText);
}
});
}
});
}
}
}
now my problem is creating the WEB API for this.
$(element.form).ajaxSubmit({
url: url, //WEB API URL
type: "POST",
dataType: "text", //I want to upload .doc / excell files
headers: { "Content-Disposition": "attachment; filename=" + fileName },
I want to upload Word/Excell document. Can someone give me an idea how to get this done in ASP.NET WEB API?
UPDATE:
I finally made an WEB API for this
public class UploadController : ApiController
{
public async Task<HttpResponseMessage> PostFormData()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
}
return Request.CreateResponse(HttpStatusCode.OK);
//return new HttpResponseMessage()
//{
// Content = new StringContent("File uploaded.")
//};
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
It works ok (data successfully uploaded) but the problem is, it seems like in doesnt hit this section after the data is succesfully uploaded.
success: function (data) {
$(".progress").hide();
$(".progressError").hide();
// set viewModel property to filename
bindingContext.$data[property](data);
},
I have to inform the client of what the status of the upload.