- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) > web開(kāi)發(fā) > JavaScript >
- node.js使用express-fileupload中間件實(shí)現文件上傳
本文使用express作為服務(wù)端,使用express-fileupload庫提供的中間件函數來(lái)接受從客戶(hù)端傳來(lái)的圖片,并將圖片作為文件存儲在服務(wù)端??蛻?hù)端使用create-react-app框架,bootstrap UI,axios發(fā)送http請求和提供進(jìn)度條當前進(jìn)度的值,上傳成功后,根據圖片在服務(wù)端上的位置,并顯示圖片。
mkdir react-file-upload // 創(chuàng )建項目根目錄 cd react-file-upload npm init -y // 初始化 npm 創(chuàng )建 package.json
安裝一些必要依賴(lài)(dependencies)
npm i express express-fileupload npm i -D nodemon concurrently // 可以并行同時(shí)運行客戶(hù)端和服務(wù)端(在本機進(jìn)行測試)
更改 react-file-upload/package.json 中的 scripts 腳本
{ "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\" " } }
下面來(lái)編寫(xiě) server.js 文件
const express = require('express'); const fileUpload = require('express-fileupload'); const app = express(); // 使用 express-fileupload 中間件 app.use( fileUpload() ); // 處理由 /upload 頁(yè)面發(fā)送過(guò)來(lái)的post請求 app.post('/upload', (req, res) => { // req 中的 files 屬性由 express-fileupload 中間件添加!? (疑問(wèn)暫存) // 判斷 files 屬性是否存在 和 是否有文件傳來(lái) 若無(wú)返回400 if(req.files === null){ return res.status(400).json({msg:'no file uploaded'}); } // 否則 獲取文件 // file 由后文中 formData.append('file', file) 的第一個(gè)參數定義 可自定義為其他名稱(chēng) const file = req.files.file; // 移動(dòng)文件到第一參數指定位置 若有錯誤 返回500 file.mv(`${__dirname}/client/public/uploads/${file.name}`, err => { if(err){ console.error(err); return res.status(500).send(err); } // 若無(wú)錯誤 返回一個(gè) json // 我們計劃上傳文件后 根據文件在服務(wù)器上的路徑 顯示上傳后的文件 // 隨后我們會(huì )在 react 組件中實(shí)現 // 在客戶(hù)端中的 public 文件夾下創(chuàng )建 uploads 文件夾 用于保存上傳的文件 res.json({fileName: file.name, filePath: `uploads/${file.name}`}); }); }); app.listen(5000,() => {console.log('Server started...')});
現在運行一遍 server.js 保證無(wú)錯誤 會(huì )在控制臺看到 Server started...
npm run server
然后我們創(chuàng )建客戶(hù)端 我們使用 create-react-app 腳手架初始化項目
npx create-react-app client
初始化完成后 我們可以先選擇性的刪除一些不必要的文件
我們刪除 src / index.js 文件中引入的 index.css,在 public 文件夾中的 index.html 模板文件中,直接引入bootstrap 的 css 和 js
<!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" 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>
我們總共需要編寫(xiě)3各組件,分別為
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
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
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
目前為止,全部的功能組件都已完成。
npm run dev
最后附上git地址
到此這篇關(guān)于node.js使用express-fileupload中間件實(shí)現文件上傳的文章就介紹到這了,更多相關(guān)node.js 文件上傳內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。
Copyright ? 2009-2022 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 特網(wǎng)科技 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 百度云 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站