当前位置:网站首页>Express file upload
Express file upload
2022-06-30 09:16:00 【The man of Jike will never admit defeat】
Express の Upload files
Last article About file downloading . In fact, you can see for yourself multer Project documentation . I wrote it myself according to this .multer Handle multipart/form-data Type of POST request , That is, file uploading . Of course, forms without files are OK .
install multer
npm install --save multer
Single file upload
multer stay request Added... To the object file perhaps files Property is used to receive a single file or multiple files in the form .
<form action="http://localhost:3000/uploadSingle" method="post" enctype="multipart/form-data">
<input type="text" name="username" placeholder=" Please enter a name "/><br>
<input type="password" name="password" placeholder=" Please input a password "/><br>
<input type="file" name="resume" id="resume"><br>
<button type="submit"> Submit </button>
</form>
app.post('/uploadSingle', upload.single('resume'), (req, res) => {
let resume = req.file;
console.dir(resume);
let {
username, password } = req.body;
console.log(username);
console.log(password);
res.setHeader('Content-Type', 'text/plain');
res.send(JSON.stringify(req.body));
});
First ,express Will be created under the current path temp Folders are used to store uploaded files . Then look at the printed content
{
fieldname: 'resume', // html <input type="file"> Labeled name Property value
originalname: 'if.pdf', // Uploaded file name
encoding: '7bit',
mimetype: 'application/pdf', // Media type of file
destination: 'temp/', // File save location
filename: '2f84eb8d718b7cb27ba9a38bd1d884c1', // stay destination File name in
path: 'temp\\2f84eb8d718b7cb27ba9a38bd1d884c1', // File full path
size: 3020009 // file size , Company : byte
}
The obvious problem is , The uploaded file is a random name . Why? ? Source code in multer() There is a paragraph in the comment of the function . If you call multer() Function is not storage Parameters and only dest Parameters , The file will be stored in a random name dest A designated place .
The
StorageEnginespecified instoragewill be used to store files. Ifstorageis not set anddestis, files will be stored indeston the local file system with random names. If neither are set, files will be stored in memory.
To solve this problem , Intuition is simple , Just change the file name . Yes , Change the file name
app.post('/uploadSingle', upload.single('resume'), (req, res) => {
let resume = req.file;
console.dir(resume);
fs.renameSync('temp/' + resume.filename, 'temp/' + resume.originalname);
res.setHeader('Content-Type', 'text/plain');
res.send(JSON.stringify(req.body));
});

Dangdang Dangdang , Be accomplished .
wait , There seems to be some helplessness , After all, the file name itself has , Why do you need another line of code . also , If the storage location needs to be changed in the future , Every function has to be changed , It's not worth it .
Disk storage
multer The object provides diskStorage Method allows you to configure how uploaded files are stored in the file system . This object has two properties
destination: Where the uploaded files are stored . It can be a string or a function . If it is a string type and the position does not exist ,multerWill recursively create . If you pass neither string nor function , The file will be stored in the temporary directory of the operating systemos.tmpdir()Next .windows Of lenovo The user temporary directory is
filename: It can only be a function . If you don't transfer functions ,multerWill use pseudo-random without extension 32 Hexadecimal string named file .- The two properties above , If the value passed is a function type , The arguments to the function are the same , Namely
requst: GeneralRequestobject .file: Object for uploading file related information .callback: Callback function . The first parameter of the callback function isError, That is, if an exception occurs to the exception object , The second parameter isPath to save file (destination)orfile name (filename). The official document writes this parameter ascb, I can't understand what it means
Post a complete code
const express = require('express');
const multer = require('multer');
let app = express();
let storage = multer.diskStorage({
destination: function (req, file, callback) {
// Note that relative paths are supported here
callback(null, '../resource');
},
filename: function (req, file, callback) {
callback(null, file.originalname);
}
});
// The abbreviated form of attribute value is used here , Not familiar with js Your classmates may have to make up for the missed lessons .
const upload = multer({
storage });
app.post('/uploadSingle', upload.single('resume'), (req, res) => {
let resume = req.file;
console.dir(resume);
res.setHeader('Content-Type', 'text/plain');
res.send(JSON.stringify(req.body));
});
app.listen('3000', () => {
console.log('server started...');
});
Execute the code again , Will be in resource The file we uploaded appears in the directory . Personal test : Uploading multiple files with the same name will cause overwriting , So you can add a timestamp or random number when defining the file name .
Multiple file upload
The new demand : The form of sending resumes not only needs to upload resumes , You also need to upload your ID photo . therefore , A form should have two places to upload files .
<form action="http://localhost:3000/uploadMany" method="post" enctype="multipart/form-data">
<input type="text" name="username" placeholder=" Please enter a name "/><br>
<input type="password" name="password" placeholder=" Please input a password "/><br>
<input type="file" name="resume" id="resume"> resume <br>
<input type="file" name="logo" id="logo2"> Head portrait <br>
<button type="submit"> Submit </button>
</form>
When receiving files , We need to deal with different files separately .
First , Define which files to receive , Maximum number of files per type . Use multer Example of fields Method , This method receives an array of objects as parameters , Each object has the following two properties
name: Corresponding forminput type="file"OfnameattributemaxCount: The maximum number of files received . The default isInfinityInfinite number
const upload = multer({
storage });
let filesToReceive = upload.fields([
{
name: 'resume', maxCount: 1 },
{
name: 'logo', maxCount: 1 },
]);
then , take filesToReceive Pass to POST Route the processing method and get the file information . Note that when you get the file information, you use files attribute ,files It's an object , Key is a string , Values are arrays .
app.post('/uploadMany', filesToReceive, (req, res) => {
let resume = req.files['resume'][0];
let logo = req.files['logo'][0];
console.log(resume);
console.log(logo);
res.setHeader('Content-Type', 'text/plain');
res.send(JSON.stringify(req.body));
});
Take a look at the printed content
{
fieldname: 'logo',
originalname: 'logo.txt',
encoding: '7bit',
mimetype: 'text/plain',
destination: '../resource',
filename: 'logo.txt',
path: '..\\resource\\logo.txt',
size: 0 // An empty one txt
}
No file upload
No file upload is easy to understand , Just use none() Method . Below is a common form that does not upload any files
<form action="http://localhost:3000/uploadNone" method="post" enctype="multipart/form-data">
<input type="text" name="username" placeholder=" Please enter a name "/><br>
<input type="password" name="password" placeholder=" Please input a password "/><br>
<button type="submit"> Submit </button>
</form>
app.post('/uploadNone', upload.none(), (req, res) => {
let {
username, password } = req.body;
res.setHeader('Content-Type', 'text/plain');
res.send(JSON.stringify(req.body));
});
If you force a file to upload , Ah , People report mistakes to you MulterError: Unexpected field
File restrictions limits
Look at the content above , You will know multer Many default values are worse , It can upload the most Infinity File . therefore , It is necessary to filter the uploaded files , Avoid malicious form submissions .
Let's set the maximum upload file size 1024B, namely 1KB. In the structure multer The instance specifies limits Object is used to restrict file uploading .
fileSize: Maximum file length . Companybyte. Default infinityfiles: Maximum number of uploaded files . Default infinityfields: The maximum number of non file fields in the upload object . Default infinity- etc.
const upload = multer({
storage,
limits: {
// Company byte
fileSize: 1024
}
});
If the upload exceeds the maximum number , You're going to report a mistake 
File filtering FileFilter
The previous example is good , If we just want users to upload resumes and ID photos , That means we only accept PDF and JPG/JPEG/PNG File format , Other 、 Files that may harm the server , such as .sh/.bat/.exe file , Reject all Or neglect , Where you come from, where you go .
Use fileFilter Customize our file filtering . This method takes three parameters
requst: GeneralRequestobject .file: An object that contains information about the uploaded file .callback: Callback function , Two parameters , The first parameter isErrorobject , No abnormal transmissionnull. The second parameter isbooleanvalue , Pass ontrueIndicates that upload is allowed ,falseIt means that it is not allowed to .
const upload = multer({
storage,
limits: {
fileSize: 1024
},
// File filter
fileFilter: function (req, file, callback) {
if (file.originalname.indexOf('.sh') !== -1 || file.originalname.indexOf('.exe') !== -1) {
callback(new Error(' It is not allowed to upload messy files '), false);
} else if (file.originalname.indexOf('.pdf') !== -1 || file.originalname.indexOf('.jpeg') !== -1) {
callback(null, true);
}
}
});
I test upload a exe file , See the effect ha ha 
exception handling
The above limits and filters the files , Actually … Not very friendly. After all, it's not professional to directly return the error exception to a user , So we need to catch such exceptions and wrap them .
multer The official website says don't put multer Used as a global middleware , So we did not do this in the above examples . Now we follow the official website , Slightly change the code uploaded from a single file
Before the change
const upload = multer({
... });
app.post('/uploadSingle', upload.single('resume'), (req, res) => {
let resume = req.file;
console.dir(resume);
res.setHeader('Content-Type', 'text/plain');
res.send(JSON.stringify(req.body));
});
After modification . Notice here that I modified the upload exe Type of exception thrown when file
const upload = multer({
storage,
// File restrictions
limits: {
// Maximum file 1024(1KB), Company byte
fileSize: 1024
},
// File filter
fileFilter: function (req, file, callback) {
if (file.originalname.indexOf('.sh') !== -1 || file.originalname.indexOf('.exe') !== -1) {
callback(new multer.MulterError(' I didn't expect you to upload this file ', ' It is not allowed to upload messy files '), false);
} else if (file.originalname.indexOf('.pdf') !== -1 || file.originalname.indexOf('.jpeg') !== -1) {
callback(null, true);
}
}
});
let singleUpload = upload.single('resume');
app.post('/uploadSingle', (req, res) => {
singleUpload(req, res, (err) => {
// If it is Multer It's abnormal
if (err instanceof multer.MulterError) {
res.json(err);
return;
} else if (err) {
// Other anomalies
res.json(err);
return;
}
let resume = req.file;
res.setHeader('Content-Type', 'text/plain');
res.send(JSON.stringify(req.body));
});
});
Upload again exe When you file , It will give you a wrong message . You can encapsulate the global unified exception return again .
Okay , Upload is temporarily written here
边栏推荐
- Qt连接神通数据库
- Row column (vertical and horizontal table) conversion of SQL
- Icon resources
- Deep Learning with Pytorch- neural network
- Treatment process record of Union Medical College Hospital (Dongdan hospital area)
- Six implementation methods of singleton mode
- Deeply understand the working principle of kotlin collaboration suspend (beginners can also understand it)
- Splice and slice functions of JS
- Is it safe to open an account? How can anyone say that it is not reliable.
- ES6 learning path (III) deconstruction assignment
猜你喜欢

使用华为性能管理服务,按需配置采样率

Qt连接神通数据库

Detailed explanation of pipline of mmdetection

Opencv learning notes-day14 drawing of image geometry (rect class rotatedrect class, rectangle drawing rectangle circle drawing circular function line drawing line function ellipse drawing elliptic fu

Opencv learning notes -day4 image pixel reading and writing operations (array traversal and pointer traversal implementation, uchar vec3b data type and mat class functions mat:: at(), mat:: ptr())

Tutorial for beginners of small programs day01

Metasploit practice - SSH brute force cracking process

Talk about the kotlin cooperation process and the difference between job and supervisorjob

Mmcv expanding CUDA operator beginner level chapter

Flink SQL custom connector
随机推荐
Flink SQL custom connector
Introduction to MySQL basics day3 power node [Lao Du] class notes
Applet learning path 2 - event binding
Is it safe to open an account? How can anyone say that it is not reliable.
Design specification for smart speakers v1.0
Comparison of two ways for C to access SQL Server database (SqlDataReader vs SqlDataAdapter)
RPC understanding
Based on svelte3 X desktop UI component library svelte UI
Use V-IF with V-for
Influencing factors of echo cancellation for smart speakers
Raspberry pie 4B no screen installation system and networking using VNC wireless projection function
Rew acoustic test (V): equipment required for test
Mmdet line by line deltaxywhbboxcoder
7. know JNI and NDK
5. Messager framework and imessager interface
Esp32 things (VIII): music playing function of function development
Invalid update: invalid number of sections. The number of sections contained in the table view after
Coredata acquisition in swift sorting, ascending, descending
Pytorch BERT
Esp32 (4): overview of the overall code architecture