gpt4 book ai didi

node.js - 在node中结合multer和tinypng API

转载 作者:太空宇宙 更新时间:2023-11-03 21:57:09 25 4
gpt4 key购买 nike

有谁知道怎么用tinyPNG's API与穆尔特?这些文档看似简单:

var source = tinify.fromFile("unoptimized.jpg");
source.toFile("optimized.jpg");

尽管没有明确的迹象表明这将走向何方,尤其是在像这样复杂的事情中:

var storage =  multer.diskStorage(
{
destination: function (req, file, callback) {
callback(null, './uploads');
},

filename: function (req, file, callback) {
//use date to guarantee name uniqueness
callback(null, file.originalname + '-' + Date.now());
}
}
);

//.any() allows multiple file uploads
var upload = multer({ storage : storage}).any()

app.post('/api/photo', function(req,res){

upload(req,res,function(err) {

if(err) {
return res.end("Error uploading file.");
}

res.end("File is uploaded");
});
});

我应该在哪里“拦截”multer上传的文件,以便我可以用tinyPNG压缩它?

预先感谢您的帮助!

最佳答案

使用以下基本示例来更改上传的照片/图库文件:

// Import express and multer.
var express = require('express');
var multer = require('multer');

// Setup upload.
var upload = multer({ dest: 'uploads/' });
var multipleFiles = upload.fields([{ name: 'photo', maxCount: 1 },
{ name: 'gallery', maxCount: 8 }]);

// Setup tinify.
var tinify = require("tinify");
tinify.key = "YOUR_API_KEY";

// Get request handler for '/' path.
var app = express();
app.get('/', function (req, res) {
res.setHeader("Content-Type", "text/html");
res.end(
"<form action='/api/photo' method='post' enctype='multipart/form-data'>" +
"<input type='file' name='photo' />" +
"<input type='file' name='gallery' multiple/>" +
"<input type='submit' />" +
"</form>"
);
});

// Upload file handler with '/api/photo' path.
app.post('/api/photo', multipleFiles, function (req, res) {
req.files['gallery'].forEach(function(file) {
// Your logic with tinify here.
var source = tinify.fromFile(file.path);
source.toFile(file.path + "_optimized.jpg");
});

res.end("UPLOAD COMPLETED!");
});

您可以根据需要随意更改 express 中间件,只需确保使用 upload.fields 并使用 tinify.key = "YOUR_API_KEY"进行身份验证即可;

关于node.js - 在node中结合multer和tinypng API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37633991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com