[英]Upload file to Dropbox from node.js
I am trying to upload a file from Node.js to my dropbox account.我正在尝试将文件从 Node.js 上传到我的 Dropbox 帐户。 I have created an app on dropbox developer console and then generated a Access Token.
我在 Dropbox 开发者控制台上创建了一个应用程序,然后生成了一个访问令牌。
I am using the following code to read and upload a file to dropbox:我正在使用以下代码读取文件并将其上传到保管箱:
app.get('/uploadfile', function (req, res) {
if (req.query.error) {
return res.send('ERROR ' + req.query.error + ': ' + req.query.error_description);
}
fs.readFile(__dirname + '/files/pictureicon.png','utf8', function read(err, data) {
if (err) {
throw err;
}
fileupload(data);
});
});
function fileupload(content) {
request.put('https://api-content.dropbox.com/1/files_put/auto/proposals/icon.png', {
headers: { Authorization: 'Bearer TOKEN-HERE', 'Content-Type': 'image/png'
}, body: content}, function optionalCallback (err, httpResponse, bodymsg) {
if (err) {
return console.log(err);
}
console.log("HERE");
});
}
By using the above code my file appears in my dropbox account but I am unable to open it.通过使用上面的代码,我的文件出现在我的保管箱帐户中,但我无法打开它。 It comes up with the following error.
它出现了以下错误。
Any idea what I could be doing wrong?知道我可能做错了什么吗? Am I making a mistake in the code above?
我在上面的代码中犯了错误吗?
The problem is probably that you read the file with the encoding utf-8
, even though it is not a text file.问题可能是您使用编码
utf-8
读取文件,即使它不是文本文件。 You should read the buffer (by simply not providing a encoding argument ).您应该读取缓冲区(通过简单地不提供编码参数)。
I know it is a bit late hope this will help someone,我知道现在有点晚了希望这会帮助某人,
const axios = require('axios');
const fs = require('fs');
const uploadFile = async () => {
try {
const response = await axios({
method: `POST`,
url: `https://content.dropboxapi.com/2/files/upload`,
headers: {
Authorization: `Bearer ${AUTH_TOKEN}`,
'Content-Type': 'application/octet-stream',
'Dropbox-API-Arg': '{"path":"/testfolder/isp.png"}',//file path of dropbox
},
data: fs.createReadStream(__dirname + '/isp.png'),//local path to uploading file
});
console.log(response.data);
} catch (err) {
return console.log(`X ${err.message}`);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.