Home > Web Front-end > JS Tutorial > A brief discussion on how node implements image uploading

A brief discussion on how node implements image uploading

青灯夜游
Release: 2021-03-05 10:02:51
forward
3846 people have browsed it

This article will introduce to you how node implements image file uploading. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

A brief discussion on how node implements image uploading

Related recommendations: "nodejs Tutorial"

In web development, file upload is a very important issue, especially Image uploading, as well as the extended "progress bar", "file size", and the famous "cross-domain" issues.

This demo demonstrates the uploading of images, and the server code is node.

Front-end part

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
  <input type="file" name="file" accept="image/*" onchange="changeImg(event)"/>
  <button onclick="submit()">上传</button>

  <script>
    let file = ''
    let fileName = ''

    function submit() {
      let data = new FormData()
      data.append('imgName', fileName)
      data.append('img', file)

      axios({
        method: 'post',
        timeout: 2000,
        url: 'http://localhost:8081/postApi',
        data: data
      })
        .then(response => {
          console.log(response.data)
        })
        .catch(error => {
          console.log(error)
        })
    }

    function changeImg(e) {
      file = e.target.files.item(0)   //只能选择一张图片
      // 如果不选择图片
      if (file === null) {
        return
      }
      fileName = file.name
    }
  </script>
</body>
</html>
Copy after login

adoptingUse axios to send requests——In fact, we can also use another "cross-domain request method" here ( vue-resource), but I thought about it here. Or use the backend setting cross-domain method.

Backend part

This is the focus of this article. In order to parse file upload requests in an efficient and smooth way, we first introduce formidableLibrary:

npm install formidable --save
Copy after login

formidable's streaming parser makes it an excellent choice for handling file uploads, meaning it can receive chunks of data as they are uploaded, parse them, and spit out specific parts , I believe friends who are familiar with the flow will understand it easily. This method is not only fast, but also does not cause memory expansion due to the need for a large amount of buffering. Even large files such as videos will not overwhelm the process.
Of course, we need to create the myImage file to store the uploaded images. Then, we create an IncomingForm instance form and set the storage path to the myImage folder. The code is as follows:

const http=require('http');
const formidable=require('formidable');

var server=http.createServer(function(req,res){
	// 后端设置跨域
	res.setHeader('Access-Control-Allow-Origin','*');
	res.setHeader('Access-Control-Allow-Headers','Content-Type');
	res.setHeader('Content-Type','application/json');
	
	switch(req.method){
		case 'OPTIONS':
			res.statusCode=200;
			res.end();
			break;
		case 'POST':
			upload(req,res);
			break;
	}
})

function upload(req,res){
	if(!isFormData(req)){
		res.statusCode=400;
		res.end('请求错误,请使用multipart/form-data格式');
		return;
	}
	
	var form=new formidable.IncomingForm();
	// 设置上传图片保存文件
	form.uploadDir='./myImage';
	form.keepExtensions=true;
	
	form.on('field',(field,value)=>{
		console.log(field);
		console.log(value);
	})
	form.on('end',()=>{
		res.end('上传完成!');
	})
	form.parse(req);
}

function isFormData(req){
	let type=req.headers['content-type'] || '';
	return type.includes('multipart/form-data');
}

server.listen(8081,function(){
	console.log('port is on 8081');
})
Copy after login

The three lines 6, 7, and 8 of setHeader are particularly important. This is the essence of back-end cross-domain!

Add upload progress

This is also what we commonly use and what we want to see! This will give users an excellent experience.
We only need to add:

	form.on('progress',(bytesReceived,bytesExpected)=>{
		var precent=Math.floor(bytesReceived/bytesExpected*100);
		console.log(precent);
	})
Copy after login

to the above code and then send the progress back to the user's browser.

formidable

The formidable module implements uploading and encoding images and videos. It supports GB-level upload data processing and supports multiple client data submissions. It has extremely high test coverage and is very suitable for use in production environments.
Methods and properties of the formidable module - around: Formidable.incomingForm()

You can create a form form through this method:

var form = new formidable.IncomingForm();
Copy after login

Set through the encoding attribute Field encoding

form.encoding='utf-8';
Copy after login

Use uploadDir to set the location where temporary files are stored when uploading files. The default uploaded temporary file storage location is os.tmpDir();

form.uploadDir='/tmp/';
Copy after login

File upload can be set through the keepExtensions attribute. Whether the file name of the temporary file includes the extension. If this value is true, the extension is included; otherwise, the extension is not included.

form.keepExtensions=false
Copy after login

There is also a more important "parse method": parsing the data submitted by the form contained in the request request in node.js. cb is the callback function for processing requests (not required).

form.parse(req,function(err,fields,files){
    //...
});
Copy after login

For more programming-related knowledge, please visit: Programming Video! !

The above is the detailed content of A brief discussion on how node implements image uploading. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template