express-fileupload to Google Drive API

混江龙づ霸主 提交于 2021-01-27 19:43:00

问题


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.

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]}

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

回答1:


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.

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

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



回答2:


Thats because you are only uploading the file metadata you need to actually upload the file.

var media = {
        mimeType: 'image/jpeg',
        //PATH OF THE FILE FROM YOUR COMPUTER
        body: fs.createReadStream('C:/Users/me/Downloads/photo.jpg')
};


来源:https://stackoverflow.com/questions/58851466/express-fileupload-to-google-drive-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!