1 回答

TA貢獻1155條經驗 獲得超0個贊
我相信你的目標和情況如下。
您想要使用 Drive API 將文件上傳到 Google Drive?
multipart/form-data
。您的訪問令牌可用于將文件上傳到 Google 云端硬盤。
我認為在您的情況下,元數據和文件內容不能上傳為multipart/form-data
.?這樣,文件元數據就無法反映到上傳的文件中。所以為了實現這一點,我想提出以下修改。
模式 1:
在此模式中,const request = require("request")
使用。
修改腳本:
const fs = require("fs");
const request = require("request");
token = req.body.token;
fs.readFile("./all.vcf", function (err, content) {
? if (err) {
? ? console.error(err);
? }
? const metadata = {
? ? name: "all.vcf",
? ? mimeType: "text/x-vcard"
? };
? const boundary = "xxxxxxxxxx";
? let data = "--" + boundary + "\r\n";
? data += 'Content-Disposition: form-data; name="metadata"\r\n';
? data += "Content-Type: application/json; charset=UTF-8\r\n\r\n";
? data += JSON.stringify(metadata) + "\r\n";
? data += "--" + boundary + "\r\n";
? data += 'Content-Disposition: form-data; name="file"\r\n\r\n';
? const payload = Buffer.concat([
? ? Buffer.from(data, "utf8"),
? ? Buffer.from(content, "binary"),
? ? Buffer.from("\r\n--" + boundary + "--\r\n", "utf8"),
? ]);
? request(
? ? {
? ? ? method: "POST",
? ? ? url:
? ? ? ? "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
? ? ? headers: {
? ? ? ? Authorization: token,
? ? ? ? "Content-Type": "multipart/form-data; boundary=" + boundary,
? ? ? },
? ? ? body: payload,
? ? },
? ? function (err, resp, body) {
? ? ? if(err){
? ? ? ? console.log(err);
? ? ? }else{
? ? ? ? console.log('resp',body);
? ? ? ? res.status(200).send()
? ? ? ? fs.readdir('./contacts', function (err, files) {
? ? ? ? ? ? var removefiles = function (file) {
? ? ? ? ? ? ? ? fs.unlinkSync('./contacts/' + file)
? ? ? ? ? ? }
? ? ? ? ? ? files.forEach(function (file) {
? ? ? ? ? ? ? ? removefiles(file)
? ? ? ? ? ? })
? ? ? ? })
? ? ? }
? ? }
? );
});
模式 2:
在此模式中,使用節點提取。在您的腳本中,new FormData()使用了。所以我認為這種模式可能是你期望的方向。
修改腳本:
const FormData = require("form-data");
const fetch = require("node-fetch");
const fs = require("fs");
token = req.body.token;
var formData = new FormData();
var fileMetadata = {
? name: "all.vcf",
? mimeType: "text/x-vcard",
};
formData.append("metadata", JSON.stringify(fileMetadata), {
? contentType: "application/json",
});
formData.append("data", fs.createReadStream("./all.vcf"), {
? filename: "all.vcf",
});
fetch(
? "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
? { method: "POST", body: formData, headers: { Authorization: token } }
)
? .then((res) => res.json())
? .then((json) => console.log(json))
添加回答
舉報