I. File upload

1. Multer middleware

We usually use it when we upload files. Multer is used to process form data of type multipart/form-data. First let’s install it:

cnpm install multer --save
Copy the code

2, use,

First in the form we need to set encType to the multipart/form-data form type. We also need to use the FS module to rename the file. Here is an example of a single file upload:

<! DOCTYPEhtml>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<form action="http://localhost:8080/" method="post" enctype="multipart/form-data">
			<input type="file" name="files" value="Specified file">
			<br><br>
			<input type="submit" value="Upload">
		</form>
	</body>
</html>
Copy the code

The node code:

const express=require("express");
const multer=require('multer');
// Initialize the upload object
var upload=multer({dest:'./upload/'});
var fs = require('fs');


var app=express();

app.use("/",upload.single("files"),function(req,res){	//files is the name of input type="file"
	var oldFile=req.file.destination+req.file.filename;	// Specify the old file
	var newFile=req.file.destination + req.file.originalname;	// Specify a new file
	fs.rename(oldFile,newFile,function(err){
		if(err){
			res.send('Upload failed! ');
		}else{
			res.send('Upload successful! '); }}); }); app.listen(8080);
Copy the code

Here we can specify a single file to be uploaded to the upload folder in the root directory. Note that req.file returns the basic information about the file:

Fieldname: ***, // Input Type = name of "file" OriginalName: ***, // Encoding: '***', // Encoding: mimeType: ***', // MIME type of the file destination: './***/', // save path filename: ***, // save filename in destination path: ***, // complete path of the uploaded file size: ** // File size in bytesCopy the code

3. Upload multiple files

In HTML, input type=”file” requires multiple to filter. Multiple does not write to all files. On the server side, we need to change single() to array(” name “,num); To receive multiple file upload requests. Finally, rename them all. Before that, let’s take a look at what file uploads multer supports:

.single(fieldName) // Accepts a file named fieldName. .fields(fields).array(fieldName [, maxCount]) // Accepts an array of files named fieldName. MaxCount can be configured to limit the maximum number of uploads. .fields(fields) // Accepts mixed files for the specified fields. Fields is an array object with name and maxCount. .none() // Only text fields are accepted. "LIMIT_UNEXPECTED_FILE" error occurs if any files are uploaded to this mode. .any() // Accepts all uploaded files.Copy the code

Here we will show how to upload multiple files:

<! DOCTYPEhtml>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<form action="http://localhost:8080/" method="post" enctype="multipart/form-data">
			<input type="file" name="files" value="Specified file" multiple>
			<br><br>
			<input type="submit" value="Upload">
		</form>
	</body>
</html>
Copy the code

The node code:

const express=require("express");
const multer=require('multer');
var upload=multer({dest:'./upload/'});
var fs = require('fs');


var app=express();

app.use("/",upload.array("files".5),function(req,res,next){
	req.files.forEach(function(ele,index){
		console.log(ele);
		var oldFile=ele.destination+ele.filename;	// Specify the old file
		var newFile=ele.destination+ele.originalname;	// Specify a new file
		fs.rename(oldFile,newFile,function(err){
			err?console.log('Upload failed! ') :console.log('Upload successful! ');
		});
	});
	res.send("Uploaded successfully");
});

app.listen(8080);
Copy the code

In this case, we get the file information via req.files, which is an array of objects, and then rename it using a foreach loop.

4. Use limits to limit file uploads

Multer limits data by using the limits object, which allows the following parameters:

Maximum length of field name 100 bytes maximum length of fieldSize field value 1MB fields maximum number of non-file fields unlimited FileSize in multipart, fileSize in multipart, fileSize in multipart, fileSize in multipart In the multipart form, key pairs Max number of pairs 2000 If you upload files beyond these Settings, the MulterError module will be enabled, The module in node_modules/multer/lib/multer - error. Js:Copy the code

We can use Err. code to locate the error, which has 7 code modes. Different Settings will return different codes.

LIMIT_PART_COUNT
LIMIT_FILE_SIZE
LIMIT_FILE_COUNT
LIMIT_FIELD_KEY
LIMIT_FIELD_VALUE
LIMIT_FIELD_COUNT
LIMIT_FIELD_COUNT
Copy the code

Here is a simple example: HTML remains unchanged, js code is as follows:

const express=require("express");
const multer=require('multer');
var upload=multer({dest:'./upload/'.limits: {fileSize: 1024 * 1024 * 20.files: 5}});
var fs = require('fs');

var app=express();

app.use("/",upload.array("files".5),function(req,res,next){
	req.files.forEach(function(ele,index){
		var oldFile=ele.destination+ele.filename;	// Specify the old file
		var newFile=ele.destination+ele.originalname;	// Specify a new file
		fs.rename(oldFile,newFile,function(err){
			err?console.log('Upload failed! ') :console.log('Upload successful! ');
		});
	});
	next();
	res.send("Upload successful!");
});

app.use(function(err,req,res,next){
	if (err.code==='LIMIT_FILE_SIZE'){
		res.send('File is too large');
	}else if(err.code==='LIMIT_FILE_COUNT'){
		res.send('Too many files');
	}
})

app.listen(8080);
Copy the code

5, Ajax image upload

Picture upload implementation steps

By listening to the input change event with jquery, we can get the information of the uploaded picture stream, such as the address, size, format and name of the picture

ImgName, imgSrc, and imgFile are used to store the name, URL, and image flow information of the uploaded image, respectively

var fileList = this.files;
        for(var i = 0; i < fileList.length; i++) {
            var imgSrcI = getObjectURL(fileList[i]);
            imgName.push(fileList[i].name);
            imgSrc.push(imgSrcI);
            imgFile.push(fileList[i]);
        }
Copy the code

The getObjectURL method is an address used to get a local image that can be displayed using this URL

function getObjectURL(file) {
    var url = null ;
    if (window.createObjectURL! =undefined) { // basic
        url = window.createObjectURL(file) ;
    } else if (window.URL! =undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file) ;
    } else if (window.webkitURL! =undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file) ;
    }
    return url ;
}
Copy the code
Controls the size, format, and number of uploaded images
    $('#upload').on('change'.function(){        
          if(imgSrc.length==4) {return alert("Upload a maximum of 4 images.");
        }
        var imgSize = this.files[0].size;  //b
        if(imgSize>1024*1024*1) {//1M
            return alert("Upload pictures no more than 1M");
        }
        if(this.files[0].type ! ='image/png' && this.files[0].type ! ='image/jpeg' && this.files[0].type ! ='image/gif') {return alert("Picture upload format is not correct"); }})Copy the code
Preview picture

Create an addNewContent method that dynamically displays the added image and implements the image preview, which is called each time an image is uploaded

function addNewContent(obj) {
    $(obj).html("");
    for(var a = 0; a < imgSrc.length; a++) {
        var oldBox = $(obj).html();
        $(obj).html(oldBox + '<li class="content-img-list-item"><img src="'+imgSrc[a]+'" alt=""><a index="'+a+'" class="hide delete-btn"><i class="ico-delete"></i></a></li>'); }}Copy the code
Image deletion

1. Display the image delete button by listening to the mouseover event of the mouse

$('.content-img-list').on('mouseover'.'.content-img-list-item'.function(){$(this).children('a').removeClass('hide');
    });
Copy the code

2. Listen to the mouseleave event of the mouse and hide the image deletion button

$('.content-img-list').on('mouseleave'.'.content-img-list-item'.function(){$(this).children('a').addClass('hide');
    });
Copy the code

3. Get the index index attribute, delete the array elements through JS splice method, and call addNewContent method again to traverse the array of images to display the preview images

$(".content-img-list").on("click".'.content-img-list-item a'.function(){
            var index = $(this).attr("index");
            imgSrc.splice(index, 1);
            imgFile.splice(index, 1);
            imgName.splice(index, 1);
            var boxId = ".content-img-list";
            addNewContent(boxId);
            if(imgSrc.length<4) {// Displays the upload button
                $('.content-img .file').show(); }});Copy the code
Upload and submit pictures

FormData is mainly used here to assemble data parameters and submit them to the background

var formFile = new FormData();
Copy the code

ImgFile image stream array assembled into FormData

 $.each(imgFile, function(i, file){
            formFile.append('myFile[]', file);
        });
Copy the code

Add additional parameters

    formFile.append("type", type); 
        formFile.append("content", content); 
        formFile.append("mobile", mobile); 
Copy the code

Finally, the content is submitted using Ajax

 $.ajax({
            url: 'http://zhangykwww.yind123.com/webapi/feedback'.type: 'POST'.data: formFile,
            async: true.cache: false.contentType: false.processData: false.// traditional:true,
            dataType:'json'.success: function(res) {
                console.log(res); }})Copy the code

Above realizes the picture upload, picture preview and picture delete function

Jquery sets ajax properties

processData : false.// Tell jQuery not to process the sent data
contentType : false.// Tell jQuery not to set the Content-Type request header
Copy the code

Two, file download

File download is as simple as using res.download(), which can be written in three forms:

res.download('/report-12345.pdf');
Copy the code

Here is an example of downloading the selected file: HTML:

<! DOCTYPEhtml>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <form action="http://localhost:8080/" method="post" enctype="application/x-www-form-urlencoded">
            <input type="file" name="files" value="Select files to download"><br><br>
            <input type="submit" value="Download">
        </form>
    </body>
</html>
Copy the code

Js:

const express=require("express");
const bodyParser=require("body-parser");
​
var app=express();
​
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
​
app.post('/',urlencodedParser,function(req,res){
    res.download("./public/"+req.body.files,err= >{
        if(err){
            res.send("Download failed!");
        }else{
            console.log("Download successful!"); }}); }); app.listen(8080);
Copy the code

We can download it by selecting the file under the root directory public.

Date: 2021/12/13

Learning Reference Video: *www.bilibili.com/video/BV1i7…

Learning Reference document Reference section related video copywriting and courseware, only for personal learning and recording