geek machine
geek machine

Reputation: 173

Sharp error: [Error: Input file is missing]

I download the image through request, and then process the image through sharp. But there is an error that input file is missing, actually the variable body has a value.

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

Upvotes: 8

Views: 18778

Answers (2)

adi
adi

Reputation: 1130

I would like to point out the mistake I did!

If you are using multer library which after having run keeps the buffer in req.file, then make sure the file/buffer that is being passed inside sharp is correct.

The below was the code I used and I did faced the same error as mentioned in the question.(I have used multer for file upload)

 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 is an object!

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
} 

I have passed req.file which is inturn is an object which is not a file exactly.Rather the buffer attribute inside req.file is my actual file buffer that needs to be given inside sharp

So by using the below, I didn't face any error and my code works!

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

Upvotes: 8

nopassport1
nopassport1

Reputation: 1944

I found an issue on the sharp repo which outlines the solution:

the request module expects encoding to be set to receive body as a Buffer.

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

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

Upvotes: 5

Related Questions