This question has been asked before, but the answer was using API V2. The google documentation does not clarify how to create a file with its content using javascript client code. I tried using the code listed under Node, however, it only creates the file, it does not insert any content. Here is my code:
let fileMetadata = {
'name': name,
parents: [parentId]
};
let media = {
mimeType: 'text/plain',
body: 'content inside file'
};
gapi.client.drive.files.create({
resource: fileMetadata,
media,
fields: 'id'
})
.then(response => {
console.log('response: ', response);
})
.catch(() => {
console.log('something is wrong');
});
Can someone help me insert content into files please?
How about this sample script? In my environment, although gapi.client.drive.files.create() can create an empty file on Google Drive, it cannot directly upload files including contents. I think that this might not be able to upload files and metadata with the multipart/related, although this might be resolved by the future update. So now, as one of workarounds, I use XMLHttpRequest.
Before you use this sample script, please confirm the following points.
In your situation, you have already been able to create files using gapi. In my script, the access token is retrieved using gapi.
When you use this script, please set fileContent and metadata.
Sample script :
In this sample script, a text file including contents is created under a folder.
var fileContent = 'sample text'; // As a sample, upload a text file.
var file = new Blob([fileContent], {type: 'text/plain'});
var metadata = {
'name': 'sampleName', // Filename at Google Drive
'mimeType': 'text/plain', // mimeType at Google Drive
'parents': ['### folder ID ###'], // Folder ID at Google Drive
};
var accessToken = gapi.auth.getToken().access_token; // Here gapi is used for retrieving the access token.
var form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], {type: 'application/json'}));
form.append('file', file);
var xhr = new XMLHttpRequest();
xhr.open('post', 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id');
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.responseType = 'json';
xhr.onload = () => {
console.log(xhr.response.id); // Retrieve uploaded file ID.
};
xhr.send(form);
Request body :
In this script, form is as follows. This is sent to Google Drive using the create method of Drive API.
------WebKitFormBoundaryxX0XmxgooMjdUECR
Content-Disposition: form-data; name="metadata"; filename="blob"
Content-Type: application/json
{"name":"sampleName","mimeType":"text/plain","parents":["#####"]}
------WebKitFormBoundaryxX0XmxgooMjdUECR
Content-Disposition: form-data; name="file"; filename="blob"
Content-Type: text/plain
sample text
------WebKitFormBoundaryxX0XmxgooMjdUECR--
In my environment, I confirmed that this works fine. But if this didn't work in your environment, I'm sorry.
Related
i am able to upload blob to google drive using google drive api, but failing to assign filename and filepath
fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=media',{
method:'post',body:imgBlob,headers:{
'Content-Type': 'image/webp',
'Content-Disposition':`attachment;filename=${fileName}`,
'Authorization':`Bearer ${accessToken}`
}
}).then(req=>req.json()).then(res=>console.log(res)).catch(error=>console.log(error))
please assist
I believe your goal is as follows.
You want to upload a blob to Google Drive by giving the file metadata of the filename and the folder using the fetch API of Javascript
Your access token can be used for uploading a file to Google Drive.
In this case, how about the following modification?
Modified script
const folderId = "###"; // Please set your folder ID.
const filename = "###"; // Please set filename on Google Drive.
const accessToken = "###"; // Please set your access token.
const form = new FormData();
form.append('metadata', new Blob([JSON.stringify({ name: fileName, parents: [folderId] })], { type: 'application/json' }));
form.append('file', imgBlob);
fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', {
method: 'POST',
headers: { 'Authorization': `Bearer ${accessToken}` },
body: form
}).then(res => res.json()).then(res => console.log(res));
Note:
In this case, the maximum file size is 5 MB. If you want to upload a large file size, please use the resumable upload. Please be careful about this.
If the destination folder is in the shared Drive, please add supportsAllDrives=true to the query parameter of the endpoint.
Reference:
Upload file data
I'm trying to download a file from google drive, but I get a 405 Method not allowed
I have a valid token and I can upload a file, but downloading it using the fileId from the upload doesn't work. What am I doing wrong?
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.googleapis.com/upload/drive/v3/files/'+fileId);
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.onload = () => {
console.log(JSON.stringify(xhr.response,true,4));
};
xhr.send();
I believe your goal and situation as follows.
You want to download a file from Google Drive.
Your access token can be used for downloading the file from Google Drive using Drive API.
For this, I would like to propose the following modification.
Modification points:
I think that in your script, the endpoint of 'https://www.googleapis.com/upload/drive/v3/files/'+fileId cannot be used for downloading the file from Google Drive.
At Google Drive API, the method for downloading the file is different between Google Docs and others. Google Docs files are Google Document, Google Spreadsheet, Google Slides and so on.
From your question, I couldn't understand about the file type you want to download. So in this answer, I would like to propose the following 2 patterns.
Pattern 1:
When fileId is NOT Google Docs file, you can use the following script. The method of Files: get in Drive API is used. In this case, if the file of file ID is the text file, you can see the file content in the console.
Modified script:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.googleapis.com/drive/v3/files/' + fileId + '?alt=media');
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.onload = () => {
console.log(JSON.stringify(xhr.response,true,4));
};
xhr.send();
Pattern 2:
When fileId is the Google Docs file which are Google Document, Google Spreadsheet, Google Slides and so on, you can use the following script. The method of Files: export in Drive API is used.
Modified script:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.googleapis.com/drive/v3/files/' + fileId + '/export?mimeType=application%2Fpdf');
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.onload = () => {
console.log(JSON.stringify(xhr.response,true,4));
};
xhr.send();
In this case, the Google Docs file is downloaded as a PDF format. When you want to download the file as other mimeType, please set the mimeType.
Note:
In above scripts, the file is downloaded as the binary.
References:
Download files
Files: get
Files: export
How can I upload file to s3 using xmlhttprequest. I tried following way but I got error like
'Anonymous access is forbidden for this operation'.
Here is my code:
const xhr = new XMLHttpRequest();
xhr.open('PUT', "https://region.amazonaws.com/bucket-name/");
xhr.setRequestHeader('X-Amz-ACL', 'public-read');
xhr.setRequestHeader('Content-Type', 'image/png');
xhr.send({
file: file,
type: 'image/png',
name: "myfile_9898_0",
acl: 'public-read',
AWSAccessKeyId: 'aws key',
AWSSecreKeyId: 'scret_key'
});
Is there anything wrong with this code?
Can anyone help me?
you spelled SecretKey wrong.
however, anyone viewing this page (assuming it's in a html page) can steal your credentials! it's a Really Bad Idea to put secretKey anywhere - you're better to generate a 'pre-signed key' on the server with your secret. You'll also need CORS set up on your server to allow the cross-post.
I'm piecing together tutorials from the web to be able to build a tool where users can upload images offline in an HTML5 app to filesystem storage along with some personal details and when they are online, they can "sync" which uploads the files and their details to the server.
I've managed to get a simple page up that stores images in file storage & sizes them down but I am unable to figure out how to post them using XMLHttpRequest. I've managed to push just the file data and store it one by one by using php://input (taken from Upload file from HTML5 Filesystem by XMLHttpRequest) but I need it to be uploaded as a form field that I can retrieve via $_FILES.
This function in particular:
function (fileName, successFct) {
getFileSystem(function (fileSystem) {
var fd = new FormData();
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.onload = function(e) {
if (this.status == 200) {
console.log(this.responseText);
}
};
fileSystem.root.getFile(fileName, {}, function (fileEntry) {
fileEntry.file(function(file) {
fd.append('file' + i, file);
fd.append('name' + i, 'name' + i);
});
}, errorFct);
xhr.send(fd);
}
);
};
Full code can be seen # http://pastebin.com/W0x9q6YH
In upload.php if I do the following
print_r($_FILES);
print_r($_POST);
It just shows two empty arrays.
Struggling with a similar problem: one thing I noticed about your code, you do not set your Content-Type header to multipart/form-data.
I do not have a working sample yet, but I'm pretty sure to use FormData, you need that old multipart/form-data magic.
I'm trying to upload an image taken with
Webcam js
directly to Amazon S3
var dataUri = Webcam.snap();
var raw = window.atob(dataUri.replace(/^data\:image\/\w+\;base64\,/, ''));
and after I get the policy (which is correct) I do this
$.ajax({
type: 'POST',
url: amazonUploadUrl,
data: {
file: raw,
contentType: "image/jpeg",
key: key,
AWSAccessKeyId: awsAccessKey,
acl: "public-read",
policy: policy,
signature: signature,
name: "",
Filename: filename
},
dataType: "",
success: function (r1) {
}
});
I've tried sending the encoded image, the decoded image, I've tried modifying the headers. All I keep getting is this
XMLHttpRequest cannot load 'amazon s3 bucket url'. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'my local domain' is therefore not allowed access.
I've added the CORS info on the Amazon bucket.
I'm already uploading images to that bucket using plupload.
I've also uploaded images from a standard without using ajax.
I just can't seem to get this to work.
Any ideas?
Thanks
PS: I've also tried using
jquery webcam plugin
With the same result
You'll need to use the javascript FormData object and native XMLHttpRequest methods to post the data directly to s3. I've tried to do the exact same thing this morning with jQuery and ran into that error message, but native javascript APIs work.
I have a feeling jQuery isn't using CORS by default or is sending across a the wrong header somewhere.
This answer shows how to convert to a format S3 can understand, which may not be necessary in your case.
This should get you started on the form data part:
var fd = new FormData();
fd.append("contentType", "image/jpeg");
fd.append("key", key);
fd.append("AWSAccessKeyId", awsAccessKey);
fd.append("acl", "public-read");
fd.append("policy", policy);
fd.append("signature", signature);
fd.append('filename', "");
fd.append('file', raw);
var xhr = new XMLHttpRequest();
xhr.open('POST', amazonUploadUrl);
xhr.addEventListener('load', function(e) {
console.log('uploaded!', e) // Successful upload!
});
// Optionally bind to other xhr events, like error, progress, or abort.
// Using native XHR2 is nice because the progress event works and you
// can tack on upload progress counters.
xhr.send(fd);