使用 Javascript 中的提取生成 body 用于分段文件上传

Generate body for multipart file upload using fetch in Javascript

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

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);
});

如果您上传的元数据名称为 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