A brief discussion on how node implements image uploading
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.
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>
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 formidable
Library:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

To implement file upload and download in Workerman documents, specific code examples are required. Introduction: Workerman is a high-performance PHP asynchronous network communication framework that is simple, efficient, and easy to use. In actual development, file uploading and downloading are common functional requirements. This article will introduce how to use the Workerman framework to implement file uploading and downloading, and give specific code examples. 1. File upload: File upload refers to the operation of transferring files on the local computer to the server. The following is used

How to use Laravel to implement file upload and download functions Laravel is a popular PHP Web framework that provides a wealth of functions and tools to make developing Web applications easier and more efficient. One of the commonly used functions is file upload and download. This article will introduce how to use Laravel to implement file upload and download functions, and provide specific code examples. File upload File upload refers to uploading local files to the server for storage. In Laravel we can use file upload

How to solve Java file upload exception (FileUploadException). One problem that is often encountered in web development is FileUploadException (file upload exception). It may occur due to various reasons such as file size exceeding limit, file format mismatch, or incorrect server configuration. This article describes some ways to solve these problems and provides corresponding code examples. Limit the size of uploaded files In most scenarios, limit the file size

File Uploading and Processing in Laravel: Managing User Uploaded Files Introduction: File uploading is a very common functional requirement in modern web applications. In the Laravel framework, file uploading and processing becomes very simple and efficient. This article will introduce how to manage user-uploaded files in Laravel, including verification, storage, processing, and display of file uploads. 1. File upload File upload refers to uploading files from the client to the server. In Laravel, file uploads are very easy to handle. first,

How to use PHP to implement FTP file upload progress bar 1. Background introduction In website development, file upload is a common function. For the upload of large files, in order to improve the user experience, we often need to display an upload progress bar to the user to let the user know the file upload process. This article will introduce how to use PHP to implement the FTP file upload progress bar function. 2. The basic idea of implementing the progress bar of FTP file upload. The progress bar of FTP file upload is usually calculated by calculating the size of the uploaded file and the size of the uploaded file.

How to implement file upload using gRPC? Create supporting service definitions, including request and response messages. On the client, the file to be uploaded is opened and split into chunks, then streamed to the server via a gRPC stream. On the server side, file chunks are received and stored into a file. The server sends a response after the file upload is completed to indicate whether the upload was successful.

Answer: Yes, Golang provides functions that simplify file upload processing. Details: The MultipartFile type provides access to file metadata and content. The FormFile function gets a specific file from the form request. The ParseForm and ParseMultipartForm functions are used to parse form data and multipart form data. Using these functions simplifies the file processing process and allows developers to focus on business logic.

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate
