Express+React+Antd实现上传功能(前端和后端)
作者:小伙伴123456
这篇文章主要介绍了Express+React+Antd实现上传功能(前端和后端),本文通过示例代码给大家介绍的非常详细,需要的朋友可以参考下
前端部分:
1、新建React项目
终端输入:
npx create-react-app myapp
执行后初始化Reac项目就完成了。
2、安装Antd
npm install antd --save
看到antd及版本号说明安装成功。
3、使用Upload组件
import React, { useState } from 'react'; import { PlusOutlined } from '@ant-design/icons'; import { Image, Upload } from 'antd'; const getBase64 = (file) => new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result); reader.onerror = (error) => reject(error); }); const MyUpload = () => { const [previewOpen, setPreviewOpen] = useState(false); const [previewImage, setPreviewImage] = useState(''); const [fileList, setFileList] = useState([ { uid: '-1', name: 'image.png', status: 'done', url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', }, { uid: '-2', name: 'image.png', status: 'done', url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', }, { uid: '-3', name: 'image.png', status: 'done', url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', }, ]); const handlePreview = async (file) => { if (!file.url && !file.preview) { file.preview = await getBase64(file.originFileObj); } setPreviewImage(file.url || file.preview); setPreviewOpen(true); }; const handleChange = ({ fileList: newFileList }) => setFileList(newFileList); const uploadButton = ( <button style={{ border: 0, background: 'none', }} type="button" > <PlusOutlined /> <div style={{ marginTop: 8, }} > 上传图片 </div> </button> ); return ( <> <Upload action="" listType="picture-card" fileList={fileList} onPreview={handlePreview} onChange={handleChange} > {fileList.length >= 8 ? null : uploadButton} </Upload> {previewImage && ( <Image wrapperStyle={{ display: 'none', }} preview={{ visible: previewOpen, onVisibleChange: (visible) => setPreviewOpen(visible), afterOpenChange: (visible) => !visible && setPreviewImage(''), }} src={previewImage} /> )} </> ); }; export default MyUpload;
前端部分完成。
后端部分
1、初始化
创建文件夹,打开终端输入:
npm init
可以看到自动生成了package.json
接下来安装express
npm install express --save
2、安装express-generator
npx express-generator 或者 npm install express-generator
express-generator可以为我们自动生成项目骨架。
骨架搭建完毕后再执行npm install 安装依赖,接着执行npm start,项目成功运行!
访问localhost:3000,3000为默认端口,看到如下页面说明express项目搭建完成。
3、图片上传接口
在express中可以使用multer实现图片上传。
安装multer
npm install multer
import express from 'express' import multer from 'multer' const app = express() // 设置存储配置 const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'uploads/') }, filename: function (req, file, cb) { cb(null, file.fieldname + '-' + Date.now() + file.originalname) } }) const upload = multer({ storage: storage }); // 解析post请求body参数 app.use(express.urlencoded({extended: false })) app.use(express.json()) // 托管静态文件 app.use('/uploads', express.static('uploads')) // 设置跨域 app.all('*', function (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Content-Type'); res.header('Access-Control-Allow-Methods', '*'); res.header('Content-Type', 'application/json;charset=utf-8'); next(); }); // 处理上传的图片 app.post('/upload', upload.single('image'), (req, res) => { const file = req.file; console.log(file); if (!file) { return res.status(400).send('No file uploaded.'); } res.json('File uploaded successfully.'); }); import routerLogin from './router/login.js' import routerList from './router/list.js'; app.use('/api', routerLogin) app.use('/api', routerList) const port = 4000 app.listen(port, () => { console.log(`端口运行于http://127.0.0.1:${port}`); })
到此这篇关于Express+React+Antd实现上传功能的文章就介绍到这了,更多相关Express React Antd上传内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!