[英]How to send image dimension from javascript to back-end (express)
在前端,我使用 npm 包cropperjs
裁剪图像
const croppedCanvas = cropper.getCroppedCanvas();
const boxCanvas = getBoxCanvas(croppedCanvas);
const croppedImage = document.createElement('img');
croppedImage.src = boxCanvas.toDataURL();
croppedImage.onload = function () {
console.log(this.width, this.height);
}
我希望能够在 express 上抓住这个图像尺寸(宽度和高度)以使用 npm 包gm
保存具有新宽度和高度的图像,如下所示:
router.post("/upload", (req, res) => {
gm("public/images/" + sampleFile.name)
// use the '!' flag to ignore aspect ratio
.resize(width, height, '!')
.noProfile()
.write("public/images/edited/" + sampleFile.name, function (err) {
if (!err) console.log('done');
});
});
那么如何才能从前端发送图像的新宽度和高度来表达路线呢? 任何帮助我将不胜感激!
这可以通过一个小的浏览器 JS 轻松解决。 在以下代码中,您将从浏览器向服务器上的路径发送 HTTP POST 请求:
let xhr = new XMLHttpRequest();
xhr.open('post', 'http://mycoolsite.com/sendimagemeta/');
xhr.send('w=' + this.width + '&h=' + this.height);
现在我们已经向服务器发送了数据,我们需要从服务器端获取该数据。
app.use(express.urlencoded()) // Urlencoded to parse the request body
router.post('/sendimagemeta', function (req, res) {
console.log(req.body) // => Would be a JSON like this:
/*
{
"w": 123,
"h": 123 // The image's width and height
}
*/
// Now you can do your parsing with the JSON, you might need to convert it to an object or string, etc
// { ... }
// After it's parsed, we need to end the response.
res.end('Thank you.')
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.