本文使用express作为服务端,使用express-fileupload库提供的中间件函数来接受从客户端传来的图片,并将图片作为文件存储在服务端。客户端使用create-react-app框架,bootstrap UI,axios发送http请求和提供进度条当前进度的值,上传成功后,根据图片在服务端上的位置,并显示图片。
初始化项目
1 2 3 | mkdir react- file -upload // 创建项目根目录 cd react- file -upload npm init -y // 初始化 npm 创建 package.json |
安装一些必要依赖(dependencies)
1 2 | npm i express express-fileupload npm i -D nodemon concurrently // 可以并行同时运行客户端和服务端(在本机进行测试) |
更改 react-file-upload/package.json 中的 scripts 脚本
1 2 3 4 5 6 7 8 9 | { "main" : "server.js" , "script" : { "start" : "node server.js" , "server" : "nodemon server.js" , "client" : "npm start --prefix client" , "dev" : " concurrently \"npm run server\" \"npm run client\" " } } |
- main 改为 server.js
- start 使用 node 启动 express
- server 使用 nodemon 启动 express ,nodemon会监视server.js文件是否有变动 (ctrl+S) 若有变动 重新启动服务器 而node启动则不会,需要手动重启服务(ctrl+C 且改动文件后重新运行 node server.js)
- client 启动客户端 随后我们会创建 client 文件夹 编写 react 组件
- dev 使用 concurrently 同时启动服务端与客户端
编写服务器
下面来编写 server.js 文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | const express = require( 'express' ); const fileUpload = require( 'express-fileupload' ); const app = express(); // 使用 express-fileupload 中间件 app.use( fileUpload() ); // 处理由 /upload 页面发送过来的post请求 app.post( '/upload' , (req, res) => { // req 中的 files 属性由 express-fileupload 中间件添加!? (疑问暂存) // 判断 files 属性是否存在 和 是否有文件传来 若无返回400 if (req.files === null ){ return res.status(400).json({msg: 'no file uploaded' }); } // 否则 获取文件 // file 由后文中 formData.append('file', file) 的第一个参数定义 可自定义为其他名称 const file = req.files.file; // 移动文件到第一参数指定位置 若有错误 返回500 file.mv(`${__dirname}/client/ public /uploads/${file.name}`, err => { if (err){ console.error(err); return res.status(500).send(err); } // 若无错误 返回一个 json // 我们计划上传文件后 根据文件在服务器上的路径 显示上传后的文件 // 随后我们会在 react 组件中实现 // 在客户端中的 public 文件夹下创建 uploads 文件夹 用于保存上传的文件 res.json({fileName: file.name, filePath: `uploads/${file.name}`}); }); }); app.listen(5000,() => {console.log( 'Server started...' )}); |
现在运行一遍 server.js 保证无错误 会在控制台看到 Server started...
1 | npm run server |
初始化客户端
然后我们创建客户端 我们使用 create-react-app 脚手架初始化项目
1 | npx create-react-app client |
初始化完成后 我们可以先选择性的删除一些不必要的文件
- serviceWorker.js
- logo.svg
- index.css // 之后我们会用link标签从cdn引入bootstrap的
- App.test.js // 只是个小demo
我们删除 src / index.js 文件中引入的 index.css,在 public 文件夹中的 index.html 模板文件中,直接引入bootstrap 的 css 和 js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <!DOCTYPE html> < html lang = "en" > < head > < meta charset = "utf-8" /> < link rel = "shortcut icon" href = "%PUBLIC_URL%/favicon.ico" rel = "external nofollow" /> < meta name = "viewport" content = "width=device-width, initial-scale=1" /> < meta name = "theme-color" content = "#000000" /> <!-- 引入css --> < link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel = "external nofollow" integrity = "sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin = "anonymous" > < link rel = "manifest" href = "%PUBLIC_URL%/manifest.json" rel = "external nofollow" /> < title >React File Uploader</ title > </ head > < body > < noscript >You need to enable JavaScript to run this app.</ noscript > < div id = "root" ></ div > <!-- 引入js --> < script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin = "anonymous" ></ script > < script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity = "sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin = "anonymous" ></ script > < script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity = "sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin = "anonymous" ></ script > </ body > </ html > |
编写组件
我们总共需要编写3各组件,分别为
- FileUpload.js:用form标签的onSubmit和axios发送上传请求
- Message.js:显示信息 上传成功 服务器错误 或 没有选择文件
- Progress.js:用axios的onUploadProgress和bootstrap显示上传进度条
FileUpload
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import React, { useState } from 'react' import axios from 'axios' import Message from './Message' import Progress from './Progress' const FileUpload = () => { return ( <div> {message ? <Message msg={message} /> : null } <form onSubmit={onSubmit}> <div className= "custom-file mb-4" > <input type= "file" className= "custom-file-input" id= "customFile" onChange={onChange}></input> <label className= "custom-file-label" htmlFor= "customFile" >{filename}</label> </div> <Progress percentage={uploadedPercentage}></Progress> <input className= "btn btn-primary btn-block mt-4" type= "submit" value= "Upload" ></input> </form> { uploadedFile ? <div className= "row mt-5" > <div className= "col-md-6 m-auto" > <h3 className= "text-center" >{uploadedFile.name}</h3> <img style={{width: '100%' }} src={uploadedFile.filePath} alt= "" ></img> </div> </div> : <p>nothing uploaded yet...</p> } </div> ) } export default FileUpload |
Message.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import React from 'react' import PropTypes from 'prop-types' const Message = ({msg}) => { console.log( 'her' ) return ( <div className= "alert alert-info alert-dismissible fade show" role= "alert" > {msg} <button type= "button" className= "close" data-dismiss= "alert" aria-label= "Close" > <span aria-hidden= "true" >×</span> </button> </div> ) } Message.propTypes = { msg: PropTypes.string.isRequired, } export default Message |
Progress.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import React from 'react' import PropTypes from 'prop-types' const Progress = ({percentage}) => { return ( <div className= "progress" > <div className= "progress-bar" role= "progressbar" style={{ width: `${percentage}%` }} aria-valuenow={percentage} aria-valuemin= "0" aria-valuemax= "100" >{percentage}%</div> </div> ) } Progress.propTypes = { percentage: PropTypes.number.isRequired, } export default Progress |
测试
目前为止,全部的功能组件都已完成。
1 | npm run dev |
最后附上git地址 Git
到此这篇关于node.js使用express-fileupload中间件实现文件上传的文章就介绍到这了,更多相关node.js 文件上传内容请搜索自学编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持自学编程网!
- 本文固定链接: https://zxbcw.cn/post/217585/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)