前端上传图片,在egg中,要怎么拿到上传图片的原路径?
看了egg的官方教程和实例,能拿到的都是处理之后的路径,这样的路径传入sharp中就会报错,无法压缩。请问有什么方法能拿到上传图片的原路径?
相关代码
async upload() {
const { ctx } = this;
const file = ctx.request.files[0];
if (!file) return ctx.throw(404);
const filename = encodeURIComponent(ctx.request.body.name) + path.extname(file.filename).toLowerCase();
const targetPath = path.join(this.config.baseDir, 'app/public', filename);
const source = fs.createReadStream(file.filepath);
const target = fs.createWriteStream(targetPath);
// await pump(source, target);
await sharp(target)
// .rotate()
.resize(100, 100)
.toFile('/Users/lixiang/work/examples-master/multipart-file-mode/app/demo/'+ (Math.random() * 100000000).toFixed(0) +'.png', err => {
if (err) throw err;
console.log('Completed!');
})
// .then( data => {
// console.log('成功')
// console.log(data)
// })
// .catch( err => {
// console.log(err)
// } );
ctx.logger.warn('save %s to %s', file.filepath, targetPath);
// delete tmp file
await fs.unlink(file.filepath);
ctx.redirect('/public/' + filename);
}
你期待的结果是什么?实际看到的错误信息又是什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
传递入
sharp
的参数除了文件路径
外,还可以是Buffer
。所以不需要拿原路径
。况且这
原路径
1:如果是指上传用户的路径:
c://xxxx/xxx.png
,这种你拿到了,传递给sharp
也没用,因为它访问不到啊。2:如果是文件的位置,此时就应该就是上传到服务器上,保存到某个地方的文件路径,但是有点多此一举,当然如果本来原文件就要保存就另说了。
回复评论(评论贴代码好麻烦):
根据你的代码,你拿到了
stream
,那你接下来就是stream转为Buffer。npm上有库干这个,不过也可以用这个函数。可以拿到
buffer