【问题标题】:Generate body for multipart file upload using fetch in Javascript使用 Javascript 中的 fetch 为多部分文件上传生成正文
【发布时间】:2021-07-26 19:56:57
【问题描述】:

我正在尝试使用 fetch 将文件 (uploadType=multipart) 上传到 Drive API V3,但正文错误,因为它正在创建一个标题未命名的文件。

var  tmpFile=document.getElementById('inputFile').files;
 tmpFile=tmpFile[0];

await  fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', {
    method: 'POST', // or 'PUT'
    headers: {
        'Authorization': 'Bearer '+accessToken,

      },
    body: {
            metadata:{
                       'name':tmpFile.name,
                       'Content-Type':'application/json; charset=UTF-8' 
            },
            media:{
                'Content-Type': '*/*',
                'name':tmpFile
            }
    }

    })
    .then(response => response.json())
    .then(data => {
    console.log('Success:', data);
    })
    .catch((error) => {
    console.error('Error:', error);
});

【问题讨论】:

标签: javascript google-api google-drive-api fetch google-api-js-client


【解决方案1】:

如果上传的元数据名称为unnamed,则表示您的元数据未正确上传

const fs = require("fs");
const FormData = require("form-data");
const fetch = require("node-fetch");

const filePath = "./sample.txt";
const accessToken = "###";

token = req.body.token;
var formData = new FormData();
var fileMetadata = {
  name: "sample.txt",
};
formData.append("metadata", JSON.stringify(fileMetadata), {
  contentType: "application/json",
});
formData.append("data", fs.createReadStream(filePath), {
  filename: "sample.txt",
  contentType: "text/plain",
});
fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart", {
  method: "POST",
  body: formData,
  headers: { Authorization: "Bearer " + accessToken },
})
  .then((res) => res.json())
  .then(console.log);

Uploading Files of multipart/form-data to Google Drive using Drive API with Node.js

【讨论】:

    猜你喜欢
    • 2014-10-16
    • 2014-12-04
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 2018-05-24
    • 2020-09-17
    • 2021-01-19
    相关资源
    最近更新 更多