gee*_*ine 8 request node.js sharp
我通过下载图像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) });
}
})
}
});
}
Run Code Online (Sandbox Code Playgroud)
我想指出我所犯的错误!
如果您使用的 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);
});
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
我已经传递了 req.file ,它又是一个对象,它并不是一个完全文件。相反,req.file 中的 buffer 属性是我的实际文件缓冲区,需要在 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);
});
Run Code Online (Sandbox Code Playgroud)
我在sharp存储库中发现了一个问题,其中概述了解决方案:
该
request模块期望encoding被设置为接收body为Buffer.
- request(url, function(error, response, body) {
+ request({ url, encoding: null }, function(error, response, body) {
Run Code Online (Sandbox Code Playgroud)
来源:https ://github.com/lovell/sharp/issues/930#issuecomment-326833522
| 归档时间: |
|
| 查看次数: |
16282 次 |
| 最近记录: |