【问题标题】:Resizing image with busboy and sharp in firebase cloud function/Nodejs在firebase云功能/ Nodejs中使用busboy和sharp调整图像大小
【发布时间】:2019-05-17 11:47:18
【问题描述】:

上传到firebase云函数时遇到问题。我正在使用busboy和sharp来实现这一点,但每次我运行我的代码时它只返回“完成状态:'超时'”没有错误......

此代码将在没有锐化大小功能的情况下工作,请参阅下面的代码以供参考。

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

【问题讨论】:

  • 你的函数定义在哪里?您似乎没有展示全部内容。
  • @DougStevenson 编辑了我的答案是足够的信息吗?谢谢!
  • 实际上可能需要更多时间。您可以增加超时/内存限制in the console

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


【解决方案1】:

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

【讨论】:

  • 我确实将一些东西发回给客户,只是之前没有包含它,就像我说它在没有Sharp库的情况下也能工作。
  • 无法判断,因为您仍然没有显示整个代码。你被省略了一部分,我看不出它们是如何组合在一起的。
  • 我现在已经添加了所有内容。
  • 我猜你仍然没有返回结果,因为你没有正确处理承诺。我不认为您的 return data 行符合您的预期。仔细考虑数据如何在您的函数中流动,并在各处添加调试日志以查看未调用的内容。
  • 每个 then() 应该返回一个值,或者如果我删除返回数据则抛出这个显示;但在上传完成之前我不想返回任何东西。有什么建议我应该怎么做?
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 2019-01-03
    • 2019-11-15
    • 2020-03-23
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    相关资源
    最近更新 更多