express-fileupload到Google Drive API [英] express-fileupload to Google Drive API

查看:107
本文介绍了express-fileupload到Google Drive API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以成功地将上传的图像保存到我的公共上传文件夹中,并集成google drive api,但似乎正在上传一个空文件.

I can successfully save my uploaded image in my public uploads folder and integrate google drive api but it seems that it is uploading an empty file.

我应该从req.files数据中输入Google Drive API的body参数

What should I put in the body parameter of the Google Drive API from my req.files data

{name: 'country.jpg',data: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 01 00 48 00 48 00 00 ff ed 26 0c 50 68 6f 74 6f 73 68 6f 70 20 33 2e 30 00 38 42 49 4d 04 04 00 00 00 00 00 22 ... 246290 more bytes>,size: 246340,encoding: '7bit',tempFilePath: '',truncated: false,mimetype: 'image/jpeg',md5: '8890c8336c58d854d490b41fa6ec0ad4',mv: [Function: mv]}

这是我经过身份验证后的Google Drive API.

Here's my Google Drive API call after auth.

const drive = google.drive({ version: "v3", auth });
drive.files.create({
 media: {
            mimeType: "image/jpeg",
            body: // WHAT TO PUT HERE
        },
        resource: {
            name: "photo.jpg"
            // if you want to store the file in the root, remove this parents
            //parents: ['folder id in which he file needs to be stored.']
        },
        fields: "id"
    })
    .then(function(resp) {
        //console.log("RESPONSE");
        console.log(resp, "resp");
    })
    .catch(function(error) {
        console.log("ERROR");
        console.log(error);
    });

推荐答案

就像@DalmTo一样,您需要以某种方式将数据发送到Google Drive API.

Just like @DalmTo mentioned, you need to send your data to the Google Drive API somehow.

如果要在文件系统中发送文件,则可以使用她提供的代码:

If you were sending a file in your filsystem you could use the code she provided:

var media = {
  mimeType: 'image/jpeg',
  body: fs.createReadStream(FILEPATH)
};

但是,由于您没有在上传之前尝试将文件保存到文件系统中,因此必须适应您的情况.

However, since you are not trying to save the file to your filesystem before uploading you have to adapt to your situation.

由于您正在使用Express,我假设此文件通过表单上传到达您的应用程序.如果您还可以使用 multer ,则可以将文件作为

I'm assuming this files reaches your application thru a form upload since you are using Express. If you can user multer as well, you can get your files as a Buffer

然后您可以将该 Buffer 转换为 Stream

You can then convert that Buffer to a Stream.

您用于处理此问题的代码如下:

Your code for treating this would look like this:

Copyvar Readable = require('stream').Readable; 

function bufferToStream(buffer) { 
  var stream = new Readable();
  stream.push(buffer);
  stream.push(null);

  return stream;
}

app.post('/upload', upload.single('picture'), function (req, res, next) {
  // req.file is the `picture` file
  var media = {
    mimeType: 'image/jpeg',
    body: bufferToStream(req.file.buffer)
  };
})

这篇关于express-fileupload到Google Drive API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆