在Firebase云功能/ Nodejs中使用Busboy和Sharp调整图像大小

时间:2018-12-17 05:57:35

标签: node.js firebase google-cloud-functions busboy sharp

上载到firebase云函数时出现问题。.我正在使用busboy和Sharp来实现这一目标,但是每次运行代码时,它只会返回“完成状态:'超时'”,并且没有错误... < / p>

此代码无需使用锐利调整大小功能即可工作,请参阅以下代码以供参考。

const fs = require("fs");
const os = require("os");
const path = require("path");
const Busboy = require("busboy");
const config = require('../config');
const gcs = config.get('gcs');
const UUID = require('uuidv4')
const sharp = require('sharp');


 let insertStorageMaterials = (req,callback) =>{
  const busboy = new Busboy({ headers: req.headers });
  let uploadData = null;
  let origFileName;

  busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
    origFileName = filename
    const filepath = path.join(os.tmpdir(), filename);
    uploadData = { file: filepath, type: mimetype };
    file.pipe(fs.createWriteStream(filepath));

  });

  busboy.on("finish", () => {
    const bucket = gcs.bucket(bucketName);
    let uuid = UUID();

    sharp(uploadData.file)
    .resize(500, 500)
    .toFile(uploadData.file)
    .then(data => {
      console.log("data",data)
      bucket
      .upload(uploadData.file, {
        uploadType: "media",
        metadata: {
          metadata: {
            contentType: uploadData.type,
            firebaseStorageDownloadTokens: uuid
          }
        },
        destination:"Materials/test/"+origFileName  
    })
    return data
  }).then(data=>{
      let file = data[0];
      let dataURL = "https://firebasestorage.googleapis.com/v0/b/" + bucket.name + "/o/" + encodeURIComponent(file.name) + "?alt=media&token=" + uuid;
      console.log("url",dataURL)
      return callback(false,{dataURL:dataURL,name:origFileName,message:"Success!"});
    .catch(error =>{
      return error;
    })
  })

  busboy.end(req.rawBody);

  }

module.exports = {
  insertStorageMaterials:insertStorageMaterials
}

快速通话

//index.js
const app = express();
const appUsers = require('./Routes/userRoute')

const api = fbFunc.https.onRequest(app);

app.post(['/uploadMaterials'],appUsers);


module.exports = {api}

//Routes
const userFunc = require('../Functions/userFunc')

apiCalls.post('/uploadMaterials',(req,res)=>{
    userFunc.uploadMaterials(req,(err,result)=>{
      if (err) return res.status(500).send('Internal Server Error')
      return res.status(200).send(result);
  })
})

编辑:

  sharp(uploadData.file)
    .resize(500, 500)
    .toFile(uploadData.file)
    .then(data => {
      console.log("datadddd",data)
      return bucket
      .upload(uploadData.file, {
        uploadType: "media",
        metadata: {
          metadata: {
            contentType: uploadData.type,
            firebaseStorageDownloadTokens: uuid
          }
        },
        destination:"Materials/test/"+origFileName  
    })

  .then(data=>{
      let file = data[0];
      let dataURL = "https://firebasestorage.googleapis.com/v0/b/" + bucket.name + "/o/" + encodeURIComponent(file.name) + "?alt=media&token=" + uuid;
      console.log("url",dataURL)
      return callback(false,{dataURL:dataURL,name:origFileName,message:"Success!"});
    })
    .catch(error =>{
      return error;
    })

}).catch(error =>{
  return error;
})
  })

2 个答案:

答案 0 :(得分:0)

不确定问题是否在于调整大小的API,但是您是否尝试使用toBuffer方法而不是toFile?

sharp(input)
    .resize(500, 500)
    .toBuffer()
    .then(data => {
    // Convert data to image file
    });

您可以在此处使用接受的答案将图像缓冲区转换为文件-NodeJS write base64 image-file

答案 1 :(得分:0)

当您将响应发送回客户端时,HTTP函数终止。由于您从不发送响应,因此该函数将超时等待该响应。使用Express传递给您代码的res对象。