在使用ant design的upload上傳文件時,前端很好實現,那麼我們如何實現node服務端呢? 服務端文件上傳實現 前端代碼 ...
在使用ant-design的upload上傳文件時,前端很好實現,那麼我們如何實現node服務端呢?
服務端文件上傳實現
var express = require('express');
var fs = require('fs');
var path = require('path');
var multipart = require('connect-multiparty');
var router = express.Router();
/* GET App home page. */
router.get('*', function (req, res) {
res.sendFile(path.resolve('./', 'index.html'));
});
router.post('/upload', multipart(), function (req, res) {
//獲得文件名
var filename = req.files.files.originalFilename || path.basename(req.files.files.path);
//複製文件到指定路徑
var targetPath = './public/uploads/' + filename;
//複製文件流
fs.createReadStream(req.files.files.path).pipe(fs.createWriteStream(targetPath));
//響應ajax請求,告訴它圖片傳到哪了
res.json({ code: 200, data: { url: 'http://' + req.headers.host + '/public/uploads/' + filename } });
});
前端代碼
class ManageWork extends React.Component {
handleUpload(e) {
if (e.file.status === 'done') {
this.setState({ projectImage: e.file.response.data.url })
}
}
render() {
return (
<div>
<Upload name="files" action="/upload" listType="picture"
onChange={e=>this.handleUpload(e)}>
<Button type="ghost">
<Icon type="upload" /> 點擊上傳
</Button>
</Upload>
<a href={this.state.projectImage} target="_blank" className="upload-example">
<img src={this.state.projectImage} />
<span>縮略圖</span>
</a>
</div>
)
}
}