Nodejs implements file upload name

WBOY
Release: 2023-05-28 13:29:41
Original
679 people have browsed it

Name and size limit

With the continuous development of the Internet, file upload has become one of the necessary functions of many websites. In Node.js, file uploads can be implemented using a variety of modules and technologies. Below, we will introduce a file upload method based on the Express framework and discuss how to implement size and name restrictions on file uploads.

  1. Installing dependent modules

In this article we will use the Express framework as the web server and use the multer module to handle file uploads. Let’s install these dependent modules first:

npm install express multer --save
Copy after login
  1. Basic usage of file upload

The following is an example of a basic file upload routing:

const express = require('express'); const multer = require('multer'); const app = express(); const upload = multer({ dest: 'uploads/' }); app.post('/upload', upload.single('file'), function(req, res) { res.send('文件上传成功!'); }); app.listen(3000, function() { console.log('服务器已启动,端口号:3000'); });
Copy after login

In the above code, we use multer'supload.singlemethod to handle file upload. The name attribute of a single file must befile. After the upload is successful, the server returns a string.

  1. File size limit

Now let’s implement the file size limit. We can do this by specifying thelimitsattribute in the multer configuration. An example is as follows:

const upload = multer({ dest: 'uploads/', limits: { fileSize: 1024 * 1024 //限制1M } });
Copy after login

In the above example, we set the maximum size of the uploaded file to 1M (unit is bytes). If the uploaded file size exceeds this value, multer will automatically return an error. We can check for errors in the route's callback function by determining whether req.file exists. An example is as follows:

app.post('/upload', upload.single('file'), function(req, res) { // 文件大小超出限制 if (req.file.size > 1024 * 1024) { return res.status(400).send('文件大小不能超过1M'); } res.send('文件上传成功!'); });
Copy after login

In the above example, if the file size exceeds 1M, a 400 error code and an error message will be returned.

  1. File name restriction

If we want to limit the uploaded file name, we can use multer'sfileFiltermethod to achieve it. In thefileFiltermethod, we can judge the uploaded file name. If the conditions are met, continue uploading, otherwise an error will be thrown. An example is as follows:

const storage = multer.diskStorage({ destination: function(req, file, cb) { cb(null, './uploads') }, filename: function(req, file, cb) { // 只允许上传后缀名为jpg, jpeg和png的文件 if (!/.(jpg|jpeg|png)$/.test(file.originalname)) { return cb(new Error('只能上传jpg, jpeg和png格式的图片')); } //自定义文件名称 let timestamp = Date.now(); cb(null, timestamp + '.' + file.originalname.split('.').pop()); } }); const upload = multer({ storage: storage, limits: { fileSize: 1024 * 1024 //限制1M }, fileFilter: function(req, file, cb) { // 检查文件类型 if (!file.originalname.match(/.(jpg|jpeg|png)$/)) { return cb(new Error('只能上传jpg, jpeg和png格式的图片')); } // 继续上传 cb(null, true); } }); app.post('/upload', upload.single('file'), function(req, res) { res.send('文件上传成功!'); });
Copy after login

In the above example, we added afilenamemethod to judge and modify the file name before uploading the file. In addition, we also use thefileFiltermethod to determine whether the file name meets the requirements. If it does not, an error is thrown.

  1. Summary

Through the above examples, we learned to use the Express and multer modules to implement file upload and size and name restrictions. I believe readers can apply it flexibly in actual development. It is worth noting that we should implement stricter security checks and restrictions on file uploads in production environments.

The above is the detailed content of Nodejs implements file upload name. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!