【发布时间】:2021-04-20 17:11:33
【问题描述】:
我正在尝试通过SharpJS 制作图像大小调整 API,我的代码如下所示
require('dotenv').config();
const express = require('express');
const sharp = require('sharp');
const cors = require('cors');
const formidable = require('formidable');
const app = express();
app.use(cors());
app.use(express.json());
app.post('/file', async (req, res) => {
const form = formidable();
form.parse(req, (err, fields, files) => {
if (err) {
next(err);
return;
}
const imageInput = files.image.path;
sharp(imageInput)
.resize(128, 128)
.toBuffer()
.then((data) => {
console.log(data);
res.end(data)
})
.catch((err) => console.log(err));
});
});
app.listen(4000);
我真正想知道的是如何将调整大小的图像返回给客户端而不将其实际保存在服务器磁盘中? data 是缓冲区的形式,如下所示,如何将其转换回文件,以便用户可以获取他们的图像并自动下载。
// console.log(data)
<Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 00 80 00 00 00 80 08 06 00 00 00 c3 3e 61 cb 00 00 00 09 70 48 59 73 00 00 0b 13 00 00 0b 13 01 ... 12835 more bytes>
我的反应代码
import React, {useState} from 'react'
import axios from 'axios'
function App() {
const [state, setState] = useState({
file: null
})
const fileHandler = e => {
console.log(e.target.files[0]);
setState({...state, file: e.target.files[0]})
}
const fileUploader = () => {
const formData = new FormData()
formData.append('image', state.file, state.file.name);
axios.post('http://localhost:4000/file',formData).then((res) => {
console.log(res.data)
}).catch((err) => {
console.error(err)
})
}
return (
<div className="App">
<input type="file" onChange={fileHandler} />
<button onClick={fileUploader}>Send File</button>
</div>
);
}
export default App;
【问题讨论】:
标签: node.js reactjs axios fs sharp