問題描述
我已經編寫了 API 并上傳到 Heroku 服務器.當我在更改后將數據推送到 Heroku 中時,所有圖像都消失了.我不知道為什么他們沒有顯示.我發現了一些其他選項,例如直接在 Google Drive 中上傳圖片,并且我已經閱讀了相關文檔.我找不到與此相關的任何資源.
I have written API and got to upload in Heroku server. When I push the data in the Heroku after changes then all the images are gone. I don't know why they were not shown. I found some other option like images upload in Google Drive directly and I have gone through relevant documentations. I couldn't find any resources related to this.
誰能幫助我提供將文件上傳到 Google 云端硬盤的參考資料或建議?
Can anyone help me out with references or suggestions to upload files to Google Drive?
推薦答案
@KarlR 的回答很有幫助,但是代碼有它自己的錯誤.(范圍不支持文件上傳).讓我一步一步解釋這一點,以便您可以輕松地將文件上傳到 Google Drive.
@KarlR's answer is helpful, but the code has it's own faults. (The scope does not support for file uploads). Let me explain this step by step so that you can easily upload a file to Google Drive.
第 1 步:轉到 Google Drive API V3 NodeJS 快速入門
Step 1: Go to Google Drive API V3 NodeJS quickstart
按照最初的步驟,看看它是否有效.然后進行下一步.
Follow the initial steps and see whether it works. Then proceed to the next step.
第 2 步:創建一個名為 uploadFile
的函數并更改范圍以適應上傳.代碼段如下.
Step 2: Have a function named uploadFile
and change the scope to suit the uploads. The code segment is given below.
在下面的示例中,文件從 files/photo.jpg
中獲取,并重命名為 photo.jpg
并上傳到 root
Google Drive 的文件夾.
In the below example, the file is fetched from files/photo.jpg
and is renamed as photo.jpg
and uploaded to the root
folder of Google Drive.
const fs = require('fs');
const readline = require('readline');
const { google } = require('googleapis');
// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/drive.file'];
const TOKEN_PATH = 'token.json';
/**
* Create an OAuth2 client with the given credentials, and then execute the given callback function.
*/
function authorize(credentials, callback) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id, client_secret, redirect_uris[0]);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getAccessToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
* @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback for the authorized client.
*/
function getAccessToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error retrieving access token', err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) return console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
/**
* Describe with given media and metaData and upload it using google.drive.create method()
*/
function uploadFile(auth) {
const drive = google.drive({version: 'v3', auth});
const fileMetadata = {
'name': 'photo.jpg'
};
const media = {
mimeType: 'image/jpeg',
body: fs.createReadStream('files/photo.jpg')
};
drive.files.create({
resource: fileMetadata,
media: media,
fields: 'id'
}, (err, file) => {
if (err) {
// Handle error
console.error(err);
} else {
console.log('File Id: ', file.id);
}
});
}
fs.readFile('credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Drive API.
authorize(JSON.parse(content), uploadFile);
});
第 3 步:更改上傳文件的名稱
在 uploadFile
功能中,更改 name
屬性.
In the uploadFile
funciton, change the name
property.
const fileMetadata = {
'name': 'any_name_you_like'
};
第 4 步:上傳不同的文件類型
您只需在 uploadFile
函數中更改以下代碼段.請參閱 最常用的 mime 類型 以獲得您的首選文件擴展名.
You only have to change the following code segment in the uploadFile
function. See mostly used mime types for your preferred file extension.
const media = {
mimeType: 'any_mime_type',
body: fs.createReadStream('files/photo.jpg')
};
第 5 步:將文件上傳到 Google 云端硬盤上的特定文件夾
打開瀏覽器并登錄您的 Google 云端硬盤.轉到特定文件夾并查看瀏覽器 URL.如下所示.
Open the browser and log in to your Google Drive. Go to the specific folder and look at the browser URL. It will look like the following.
https://drive.google.com/drive/u/0/folders/1xxxXj_sdsdsdsd0Rw6qDf0jLukG6eEUl
1xxxXj_sdsdsdsd0Rw6qDf0jLukG6eEUl 是文件夾 ID(parentID).在 uploadFile
函數中更改以下代碼段.
1xxxXj_sdsdsdsd0Rw6qDf0jLukG6eEUl is the folder ID (parentID). Change the following code segment in the uploadFile
function.
const fileMetadata = {
'name': 'any_file_name',
parents: ['1xxxXj_sdsdsdsd0Rw6qDf0jLukG6eEUl']
};
希望這對您的要求足夠全面.
Hope this is comprehensive enough for your requirements.
這篇關于如何從 NodeJS API 將圖像上傳到谷歌驅動器的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!