当前位置:网站首页>Node+express realizes the uploading, downloading and deleting of files
Node+express realizes the uploading, downloading and deleting of files
2022-07-22 06:37:00 【Ke Xiaonan】
1. Demonstration effect
Implement a server-side static resource manager , You can upload files on the server 、 download 、 Delete and other operations , And the Chinese file name is processed . The effect is as follows :
2. Create project
This project is to use express
Created by template builder , You need to install express-generator
Template generator , Run at terminal :
$ cnpm i -g express-generator
Then in the folder path where the project needs to be created , Open the terminal and execute the following commands in sequence :
# Create project
$ express -e myapp
# Enter the project directory
$ cd myapp
# Initialization dependency
$ cnpm i
# install multer modular , Used to receive uploaded file objects on the server
$ cnpm i multer --save
After the project is created , You need to create... In the root directory of the project static
Folder !
3. Design the server route for uploading and downloading
stay routes/index.js
To write the following code :
var router = require('express').Router();
var multer = require('multer');
var fs = require('fs');
var path = require('path');
// Query the route of the file
router.get('/', function(req, res, next) {
// Read static A file in a directory
fs.readdir('./static', function(err, files){
if(err){
res.render('index', {
list: [],
msg: ' No documents available '
})
return
}
res.render('index', {
list: files,
msg: ` share ${
files.length} File `
});
})
});
// Delete the route of the file
router.get('/del', function(req,res){
// Receive parameters of file name
let {
file} = req.query
// Delete static The file in the directory
fs.unlink(`./static/${
file}`, function(err){
res.redirect('/')
})
})
// File upload route
router.post('/upload', multer({
dest: './static/' }).any(), function(req,res){
let file = req.files[0]
// Name of Assembly Document
let filename = 'static/'+ file.originalname
// Rename the successfully uploaded file ( The uploaded file is not the original name of the file by default )
fs.rename(file.path, filename, function(err){
res.redirect('/')
})
})
// File download route
router.get('/down', function(req,res){
// Receiving file name
let {
fn} = req.query
// If there is Chinese in the parameter , Need to decode
fn = decodeURI(fn)
// Determine if the file exists
fs.access(`./static/${
fn}`, function(err){
if(!err){
res.set({
// Tell the browser that this is a binary file
"Content-Type": "application/octet-stream",
// Tell the browser that this is a file to download , Use encodeURI Method , To avoid problems when downloading Chinese names
"Content-Disposition": `attachment;filename=${
encodeURI(fn)}`
})
// Use streams to read files , And respond to the client
fs.createReadStream(`./static/${
fn}`).pipe(res)
}
})
})
module.exports = router;
4. Design front-end EJS Templates
open views/index.ejs
file , The sample code is as follows :
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1> Static resource manager </h1>
<!-- For uploading files form Forms -->
<form action="/upload" method="POST" enctype="multipart/form-data" >
<input type="file" name="myfile">
<button type="submit"> Upload files </button>
</form>
<hr>
<!-- File list -->
<div style="color: blue;">
<%= msg %>
</div>
<ul>
<% list.forEach(function(item){ %>
<li style="margin: 10px 0px;">
<%=item%>
<a href="javascript:del('<%=item%>');"> Delete </a>
<a href="javascript:down('<%=item%>');"> download </a>
</li>
<% }) %>
</ul>
<script> // Request method for deleting files function del(filename){
var result = window.confirm(` Are you sure you want to delete ${
filename} Do you ?`) if(result){
window.location.href = `/del?file=${
filename}` } } // Request method for downloading files function down(filename){
var url = `/down?fn=${
filename}` window.location.href = encodeURI(url) // Processing Chinese parameters } </script>
</body>
</html>
边栏推荐
猜你喜欢
随机推荐
第2集 vmware虚拟机安装最牛B教程(13天)
Complete collection of network connection tools
设置MySQL时区
攻防演练进行时|知道创宇赵伟:让安全能力长在云上
携手HMS Core分析服务,以数据助力游戏高效增长
Rotation of 2D conversion, transform origin of 2D conversion center point and scale of 2D conversion
Document flow, box model, outer margin and default style
Call event after the grip of CAD object is edited (COM interface VB language)
Dom4j解析XML(详解)
DOM Series event object
Leetcode skimming: using stack to realize queue and string decoding
rider 切换主题
动画,及动画的基本使用
第1集 vmware虛擬機安裝最牛B教程(12天)
浮动简介和浮动特点
Idea shortcut key (day 16)
使用Lingo求解简单的线性规划问题
Western Agricultural University C plus
高度塌陷和清除浮动
Relative positioning, absolute positioning, fixed positioning, sticky positioning, absolute positioning element layout, level and transparent effect settings