问题描述
我有将多个文件从 React 上传到不同文件夹的工作代码。如何集成 tinify (https://tinypng.com/developers/reference/nodejs)?我无法理解如何使用 tinify。
我的 nodejs 代码多路复用器:
import path from 'path'
import express from 'express'
import multer from 'multer'
const router = express.Router()
const formatBytes = (bytes,decimals = 2) => {
if (bytes === 0) return '0 Bytes'
const k = 1024
const dm = decimals < 0 ? 0 : decimals
const sizes = ['Bytes','KB','MB','GB','TB','PB','EB','ZB','YB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k,i)).toFixed(dm)) + ' ' + sizes[i]
}
const storage = multer.diskStorage({
destination(req,file,cb) {
const uploadFolder = req.headers.folder
cb(null,`uploads/${uploadFolder || ''}`)
},filename(req,cb) {
cb(
null,`${
file.originalname.split('.')[0]
}-global-town-${Date.Now()}${path.extname(file.originalname)}`
.toLowerCase()
.replace(/_/g,'-')
.replace(' ','-')
)
},})
function checkFileType(file,cb) {
const filetypes = /jpg|jpeg|png|svg+xml|svg|webp|pjpeg/
const extname = filetypes.test(path.extname(file.originalname).toLowerCase())
const mimetype = filetypes.test(file.mimetype)
if (!extname && !mimetype) {
return cb(new Error('You can only upload !'),false)
}
return cb(null,true)
}
const upload = multer({
storage,fileFilter: function (req,cb) {
checkFileType(file,cb)
},}).array('imagesUp',10)
router.post('/',(req,res) => {
upload(req,res,function (err) {
if (err) {
console.log(err.message)
res.status(400).json({
status: 'Failed to load',message: err,})
} else {
const files = req.files
if (!files) {
res.status(400)
throw new Error('Please,load file')
}
let paths = []
files.map((file,index) =>
paths.push({
_id: index,name: file.filename,path: `/${file.path}`,size: formatBytes(file.size),})
)
res.status(200).json({
status: 'success',message: 'File uploaded successfully',data: paths,})
}
})
})
export default router
我打算在哪里“拦截”multer上传的文件,以便我可以用tinyPNG对其进行压缩?
或者我准备使用其他库来压缩图像,但我除了 tinify 什么都不知道。如果可以,那就在我的代码中嵌入另一个库,主要是压缩。
预先感谢您的帮助!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)