【问题标题】:Sharp error: [Error: Input file is missing]尖锐错误:[错误:输入文件丢失]
【发布时间】:2020-06-22 02:41:31
【问题描述】:

我通过request下载图片,然后通过sharp处理图片。 但是有输入文件丢失的错误,实际上变量body有一个值。

import { IADLandingPageABTest } from '@byted/ec-types';
import request from 'request';
import sharp from 'sharp';

const images: Array<keyof IADLandingPageABTest> = ['topPosterUrl', 'bottomPosterUrl'];

export default function handleImage (config: IADLandingPageABTest) {
    images.forEach(key => {
        const url = config[key];
        if (url && typeof url === 'string' ) {
           request(url, (err, response, body) => {
               //console.log('body', body);
               //body has a value
               if (!err && response.statusCode === 200) {
                sharp(body)
                .resize(100)
                .toBuffer()
                .then((data) => {
                    console.log(data.toString('base64'));
                })
                .catch( err => { console.log('error', err) });
               }
           })
        }
    });
}

【问题讨论】:

标签: node.js request sharp


【解决方案1】:

我在sharp repo 上发现了一个问题,其中概述了解决方案:

request 模块期望将encoding 设置为接收body 作为Buffer

- request(url, function(error, response, body) {
+ request({ url, encoding: null }, function(error, response, body) {

来源:https://github.com/lovell/sharp/issues/930#issuecomment-326833522

【讨论】:

    【解决方案2】:

    我想指出我犯的错误!

    如果您正在使用 multer 库,该库在运行后将缓冲区保留在 req.file 中,那么请确保在 sharp 中传递的文件/缓冲区是 正确。

    以下是我使用的代码,我确实遇到了与问题中提到的相同的错误。(我使用 multer 进行文件上传)

     sharp(req.file)
     .resize({ width: 75,height: 75 })
     .toBuffer()
     .then(data => {
       console.log("data: ",data);
       res.send("File uploaded");
     }).catch(err =>{
      console.log("err: ",err);    
     });
    

    req.file 是一个对象!

    req.file:  {
    fieldname: 'file',
    originalname: 'Sample.gif',
    encoding: '7bit',
    mimetype: 'image/gif',
    buffer: <Buffer 47 49 46 38 39 61 57 04 56 02 f7 00 31 00 ff 00 09 73 22 0c 76 
    14 33 23 ... 797643 more bytes>,
    size: 797693
    } 
    

    我已经传递了 req.file ,它又是一个对象,它不是一个文件。而是 req.file 中的缓冲区属性是我的实际文件缓冲区 需要在Sharp内给出

    所以通过使用下面的代码,我没有遇到任何错误并且我的代码可以正常工作!

     sharp(req.file.buffer)
     .resize({ width: 75,height: 75 })
     .toBuffer()
     .then(data => {
       console.log("data: ",data);
       res.send("File uploaded");
     }).catch(err =>{
      console.log("err: ",err);    
     });
    

    【讨论】:

      猜你喜欢
      • 2021-11-01
      • 2021-07-10
      • 1970-01-01
      • 2020-11-30
      • 2023-01-24
      • 1970-01-01
      • 2014-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多