node.js - 我想向我的 api 发送一个发布请求,其中正文包含 html 输入文件标记的文件路径。但我得到“C:\fakepath\Book1.xlsx”
问题描述
我想在 Drive Api 中实现文件上传。我所做的是创建一个函数来发送所选文件的文件路径。但我得到的是假路径。我对这个问题的替代解决方案持开放态度。
这是我的反应组件中的功能
onChangeFile = (e) => {
console.log(e.target.value)
this.setState({excelFilePath: e.target.value})
}
onSubmitFile = () => {
fetch("http://localhost:3001/submitForm", {
method: "post",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
excelFilePath: this.state.excelFilePath
})
})
.then(res => res.json())
.then(data => console.log(data))
.catch(console.log)
}
这是我的节点 js api,它处理将所选文件上传到 Google Drive。最后一个函数是我包含 req.body.excelFilePath 的地方
const handleSubmitForm = (req, res) => {
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'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';
// Load client secrets from a local file.
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), uploadExcel);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
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);
});
});
}
function uploadExcel(auth){
console.log(req.file)
const drive = google.drive({version: 'v3', auth});
var fileMetadata = {
'name': 'BP201',
'mimeType': 'application/vnd.google-apps.spreadsheet'
};
var media = {
mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
body: fs.createReadStream(req.body.excelFilePath)
};
drive.files.create({
resource: fileMetadata,
media: media,
fields: 'id'
}, function (err, file) {
if (err) {
// Handle error
console.error(err);
} else {
console.log('File Id:', file.id);
}
});
}
res.sendStatus(200);
}
module.exports = { handleSubmitForm: handleSubmitForm }
解决方案
推荐阅读
- python - 图像和标签不会出现在 Tkinter 中
- php - 软件包 laravel/ui 版本的 PHP 要求与您的 PHP 版本 (5.6.40) 不兼容
- sql - 如何在 afterSubmit 事件中添加 180 天以在 suiteflow 中进行转换?
- javascript - 为什么Argon模板中有这么多相同的路线?
- python-3.x - 使用 Scrapy 提取维基百科链接
- image - 为什么不总是使用本机延迟加载(图像属性加载=“lazy”)?
- arrays - Numpy:在其他布尔数组的“真”上覆盖布尔数组
- django - 如何在 django 通知中使用动作对象和目标
- amazon-s3 - 无法使用无服务器框架将图像上传到 s3,但它可以离线工作(缓冲区问题)
- r - 加快重叠加性模型 (mgcv) 的估计