search
HomeWeb Front-endJS TutorialA brief discussion on how node implements image uploading

A brief discussion on how node implements image uploading

Mar 05, 2021 am 10:02 AM
nodeupload pictureFile Upload

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

nbsp;html>


  <meta>
  <title>Title</title>
  <script></script>


  <input>
  <button>上传</button>

  <script>
    let file = &#39;&#39;
    let fileName = &#39;&#39;

    function submit() {
      let data = new FormData()
      data.append(&#39;imgName&#39;, fileName)
      data.append(&#39;img&#39;, file)

      axios({
        method: &#39;post&#39;,
        timeout: 2000,
        url: &#39;http://localhost:8081/postApi&#39;,
        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>

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

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');
})

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);
	})

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();

Set through the encoding attribute Field encoding

form.encoding='utf-8';

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/';

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

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){
    //...
});

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!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools