I am trying to share upload file using google drive API.I following this tutorial
Upload files/folder, List drive file are working fine but I want to add share functionality where file can we share with specific user.
I didn't found any solution. how to share file?
You want to share the files in Google Drive using Drive API with Javascript.
You have already been able to get and put for the files on Google Drive using Drive API.
If my understanding is correct, how about this answer? Please think of this as just one of several answers.
In order to give the permissions for the file, the method of "Permissions: create" in Drive API is used.
Sample script:
In this sample script, I prepared the function of createPermissions for your situation.
function createPermissions(fileId, body) {
gapi.client.load('drive', 'v3', function() {
gapi.client.drive.permissions.create({
fileId: fileId,
resource: body,
})
.then(function(res) {
console.log(res)
// do something
})
.catch(function(err) {
console.log(err)
// do something
});
});
}
When you use this function, please use as follows.
const fileId = "###"; // Please set the file ID.
const body = {
role: "writer",
type: "user",
emailAddress: "###" // Please set the email address of user that you want to share.
};
createPermissions(fileId, body);
When you use this script, please prepare the file ID of the file you want to share.
At above script, the file is shared with the user, which has the email address of ###, as writer and user. About the detail information of parameters, please check the official document.
Note:
Unfortunately, in your actual situation, I'm not sure where you want to use the above sample script in your script. So please add it to your script.
Reference:
Permissions: create
If I misunderstood your question and this was not the direction you want, I apologize.
Related
I was looking for a solution so that people with access to a spreadsheet could upload files through it, researching I found some solutions, but as I will need these people to upload videos through the spreadsheet, some solutions that used Blob ended up being discarded.
Searching, I found this script made by Tanaike, apparently it solves practically all problems, I thought of pulling it into the spreadsheet using an html alert, thus allowing people to upload files with sizes greater than 50mb.
The script can be found here:
Resumable Upload For WebApps
The issue is that I'm having some problems getting it to work, basically I'm getting this error when trying to upload a file:
Error: <HTML> <HEAD> <TITLE>Not Implemented</TITLE> </HEAD> <BODY BGCOLOR="#FFFFFF" TEXT="#000000"> <H1>Not Implemented</H1> <H2>Error 501</H2> </BODY> </HTML>
Other than that, I have a few questions I'd like to clear up:
1- I'm not sure if with this script people with other accounts would be able to upload the files to my Google Drive, is it possible?
2- Is it possible implement it in a button on a spreadsheet and request that the file be uploaded in the same folder as that spreadsheet?
Sorry for the amount of questions, javascript and GAS are things that are not very present in my daily life, so I have a little difficulty.
Checking the developer console, the error returned from the server is accessNotConfigured. This happens when the GCP Project doesn't have the necessary APIs enabled. To fix this you need to create a new Cloud Project:
In the Google Cloud console, go to Menu > IAM & Admin > Create a Project.
In the Project Name field, enter a descriptive name for your project.
In the Location field, click Browse to display potential locations for your project. Then, click Select.
Click Create. The console navigates to the Dashboard page and your project is created within a few minutes.
After that you need to enable the Drive API:
In the Google Cloud console, go to Menu > More products > Google Workspace > Product Library.
Click the API that you want to turn on.
Click Enable.
Finally you need to attach the GCP project to your Apps Script Project:
Determine the Project number of your Cloud project.
Open the script whose Cloud project you want to replace.
At the left, click Project Settings.
Under Google Cloud Platform (GCP) Project, click Change project.
Enter the new project number and click Set project.
After attaching the standard project the error stopped showing up for me. The reason for this is that Google changed the way Apps Script creates GCP projects so now scripts may have Default or Standard projects. Default projects are essentially more restricted so you may have to create a Standard Project in certain scenarios. One these scenarios in the documentation is "To create a file-open dialog". Tanaike's code uses the same technique as the file-open dialogs to retrieve the access token from the server, which I believe is the cause of the error.
As for your other questions:
I'm not sure if with this script people with other accounts would be able to upload the files to my Google Drive, is it possible?
Only if you deploy it as a Web App, setting it to execute with your account and available to "Anyone with a Google account". This uses your account's access token to authorize so other users will upload to your account.
Is it possible implement it in a button on a spreadsheet and request that the file be uploaded in the same folder as that spreadsheet?
As I mentioned under 1., doing it within the spreadsheet probably won't work, but you can add the parents property to the request body on the HTML side to specify the folder. You can also retrieve it dynamically by calling google.script.run. Here's a sample I modified to do this:
google.script.run.withSuccessHandler(function(at) {
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable");
xhr.setRequestHeader('Authorization', "Bearer " + at.token);
xhr.setRequestHeader('Content-Type', "application/json");
xhr.send(JSON.stringify({
mimeType: fileType,
name: fileName,
parents: at.parent
}));
xhr.onload = function() {
doUpload({
location: xhr.getResponseHeader("location"),
chunks: chunks,
});
};
xhr.onerror = function() {
console.log(xhr.response);
};
}).getAt();
That's a part of the init() function in the index.html file. The at variable originally only received the access token retrieved from the server. I just modified it so it receives an object with both the access token and the folder ID, and I included the parent folder ID in the API call. You also need to modify the getAt() function in Code.gs to actually return the folder ID:
function getAt() {
var id = SpreadsheetApp.getActiveSpreadsheet().getId()
var folder = DriveApp.getFileById(id).getParents().next().getId()
return { token: ScriptApp.getOAuthToken(), parent: [folder] }
}
There's a lot to unpack here so I advise you to check the documentation. I think you'll have to go through the Web App route if you want other users to upload the files to your Drive.
Reference:
Web Apps
Communicate with Server Functions
Files.insert
Default and Standard Projects
I am trying to create a firebase function that downloads a photo off the web via URL and uploads it to firebase storage.
Using Axios to stream the file to the bucket. it appears the file gets uploaded but i cant download or view it.
This is my code:
let fileURL = 'https://www.example.file.path.png'
let myFile = await axios.get(fileURL, { responseType: 'stream' })
let destFile = bucket.file(photoId).createWriteStream({ contentType: myFile.headers['content-type']})
myFile.data.pipe(destFile)
And here is the storage console from firebase:
I have messed around with the storage api and attempted using the upload and save functions. using axios get and write streams is the closest that I'v got to getting this to work.
Reading the example in the docs only aids in my confusion because the file is never reference in the upload function.. just the file name??
Feel like i'm almost there considering the file or rather the name of the file is there and the size and the type.. just not the content?
This problem is related with Firebase console only. There is no problem with downloading with command: gsutil cp gs://<your bucket>/yourfile . (doc) and as well it is working in Google Cloud Console in Storage browser (direct link).
However indeed file uploaded like this is not possible to be downloaded or previewed with Firebase console.
After many tries I have realized that this is related with custom metadata Access token, which underneath is calledfirebaseStorageDownloadTokens. It appears automatically if ex. you download the file directly in Firebase console.
Anyway I noticed that value of the metadata is irrelevant. According to my test if you change your createWriteStream method parameters to:
let destFile = bucket.file(photoId)
.createWriteStream({
metadata: {
contentType: myFile.headers['content-type'],
metadata: {
firebaseStorageDownloadTokens: 'canBeAnyThing'
}
}
});
The problem disappears...
A file already downloaded to Firebase Storage and affected by the issue can be fixed by adding the same metadata. In the screenshot you have provided you can see "File Location" if you open you will see link "Create new access token" or as well you can add it in GCP Storage Browser adding it manually in "Edit metadata" for such object (remember to refresh FB console in browser).
At this point we can think of why it's looks like this. I have found interesting information in github here.
I searched lot and found nothing about how to send files. Even in google documentation there is nothing about sending file using Javascript sdk.
See here https://developers.google.com/drive/v3/web/manage-uploads
So right now I'm converting the nodeJs script to javascript. And they used fs to get the readstream. And I have no idea how to do that in javascript. Closet I can get to this...
var file = uploadButton.files[0]
var fileName = uploadButton.files[0].name
var fileMetadata = {
'name': fileName
};
var media = {
mimeType: 'image/jpeg',
body: file
};
gapi.client.drive.files.create({
resource: fileMetadata,
media: media.result,
fields: 'id'
}).execute();
Above code creates the empty file with then fileName and no content inside on it.
In order to upload a file to your google drive you need to use a google request object and 'POST' the file. You can see an example in this answer. Keep in mind that you need to get your API keys in order to initialise your google drive client object.
I am trying to download a PDF from a website using Javascript in the "Code" step in Zapier. I am struggling to find documentation on how to output the file object. Here is my basic code so far. unfortunately, the file that comes back is garbage characters. Perhaps it needs to be encoded? I would also like any advice you might have on how I would modify this code if the file I wanted was on a website that required basic authentication. Any advice would be greatly appreciated:
fetch('http://www.pdf995.com/samples/pdf.pdf')
.then(function(res) {
return res.text();
})
.then(function(body) {
var output = {id: 1234, myPDF: body};
callback(null, output);
})
.catch(callback);
You're code should work fine. If you're doing something like sending an email or uploading to Dropbox, you can select "Run JavaScript" in the attachment or upload document option and choose your JavaScript action.
I've only been able to generate a PDF locally so far using res.buffer() instead of res.text() and then passing the buffer to fs.writeFile().
An user need to receive a small text file generated inside the Titanium app.
I'm trying to send an email with this file in attachments, but the documentation doesn't help me to achieve this.
I'm using Ti.Cloud.Emails to send emails.
Another approach was to save the file in the Filesystem, but I'm using the code below and I can't find the file.
file = Titanium.Filesystem.getFile( Ti.Filesystem.applicationCacheDirectory,'file.csv');
alert(file.resolve());
file.write('any text\n');
The alert gives the path: file:///data/user/0/com.myapp/cache/file.csv
Yes, I tried to use the Titanium.Filesystem.applicationDataDirectory
Still, I can't find the file, Does someone knows where the file is?. Is there another better way to give to the user the file?
Thanks
Titanium docs pretty much tells how to send email and how to add attachments into it.
First of all note that to send email, you need to run the app only on device and device must have an email account configured.
Here is the sample code for you to send email with attachments:
var text_data = 'This is your data to write inside the text file.'
// you can either use applicationDataDirectory or tempDirectory
var textFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'your_file.txt');
textFile.write(text_data);
var emailDialog = Ti.UI.createEmailDialog();
var msg = "This is the message written in the body of the email content.";
emailDialog.subject = "Titanium Rocks!";
emailDialog.toRecipients = ['abc_123#gmail.com'];
emailDialog.messageBody = msg;
emailDialog.addAttachment(textFile);
emailDialog.open();
Now if you are trying to find the file on device using any File Explorer, then you cannot find them this way because these directories are not available to public users to view or to modify (otherwise I believe anyone can steal the data of any app).