


Share an example tutorial on the implementation principle of the image upload component (React + Node)
This article mainly introduces the Node-based ReactPictureUpload component implementation example code, which is of great practical value. Friends in need can refer to it
Written in front
If the red flag does not fall, I vow to carry out JavaScript to the end! Today I will introduce the front-end and back-end implementation principles (React + Node) of the image upload component in my open source project Royal. It took me some time and I hope it will be helpful to you.
Front-end implementation
Following the idea of React componentization, I made the image upload an independent component (no other dependency), just import it directly.
1 2 3 4 5 6 7 8 9 10 |
|
The uri parameter must be passed, which is the backend interface address for image upload. How to write the interface will be discussed below.
Rendering page
The render part of the component needs to reflect three functions:
Image selection (dialog window)
Drag-able function (drag-and-drop container)
Preview-able (preview list)
UploadButton (button)
Upload completed image address and link (information list)
Main renderFunction
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
|
Rendered image preview list
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
Rendered image upload information list
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
The principle of uploading images on the front end is to construct the FormData object, append() the file object to the object, and then mount it on the XMLHttpRequest object send( ) to the server.
Get the file object
To get the file object, you need to use the change event of the input input box to get the handle parameter e
1 |
|
Then Do the following processing:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
At this time, files is an array of file objects we need, and concat it into the original files.
1 |
|
In this way, the next operation can get the currently selected image file through this.state.files.
Use Promise to handle asynchronous upload
File upload is asynchronous to the browser. In order to handle the subsequent multi-image upload, Promise is introduced here to handle asynchronous Operation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
Upload progress calculation
The advantage of using the XMLHttpRequest object to send asynchronous requests is that it can calculate the progress of request processing, which fetch does not have.
We can add event monitoring for the progress event of the xhr.upload object:
1 2 3 4 |
|
Description: The idx parameter is the index that records the multi-image upload queue
1 2 3 4 5 6 |
|
Drag-and-drop upload
Drag-and-drop files are actually very simple for HTML5, because it comes with several event listening mechanisms that can be done directly This type of processing. The following three are mainly used:
1 2 3 |
|
Browser behavior when canceling drag and drop:
1 2 3 4 |
|
Processing of dragged in files:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
More Pictures are uploaded at the same time
To support multiple picture uploads, we need to set the property at the component call:
1 2 |
|
Then we can use Promise.all() to handle asynchronous operations Queue:
1 2 3 4 5 6 7 |
|
Okay, the front-end work has been completed, and the next step is the work of Node.
Backend implementation
For convenience, the backend uses expressframework to quickly build Http services and routing. For specific projects, see my github node-image-upload. Although the logic is simple, there are still several notable points:
Cross-domain call
The backend of this project uses express, we can use res .header() sets the "allowed source" of the request to allow cross-domain calls:
1 |
|
is set to * to allow any access source, which is not very safe. It is recommended to set it to the second-level domain name you need, such as jafeney.com.
In addition to "Allow source", others include "Allow header", "Allow domain", "Allow method", "Text type", etc. Commonly used settings are as follows:
1 2 3 4 5 6 7 |
|
Ajax request under ES6
Ajax request under ES6 style is different from ES5. It will be sent before the formal request is sent. A request of type OPTIONS is used as a trial. Only when the request passes, a formal request can be sent to the server.
所以服务端路由 我们还需要 处理这样一个 请求:
1 2 3 4 5 6 7 8 |
|
注意:该请求同样需要设置跨域。
处理上传
处理上传的图片引人了multiparty模块,用法很简单:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
图片处理
Node处理图片需要引入 gm 模块,它需要用 npm 来安装:
1 |
|
BUG说明
注意:node的图形操作gm模块前使用必须 先安装 imagemagick 和 graphicsmagick,Linux (ubuntu)上使用apt-get 安装:
1 2 |
|
MacOS上可以用 Homebrew 直接安装:
1 2 |
|
预设尺寸
有些时候除了原图,我们可能需要把原图等比例缩小作为预览图或者缩略图。这个异步操作还是用Promise来实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
重命名图片
为了方便排序和管理图片,我们按照 “年月日 + 时间戳 + 尺寸” 来命名图片:
1 2 |
|
至于图片尺寸 使用 gm的 size() 方法来获取,处理方式如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
总结
对于大前端的工作,理解图片上传的前后端原理仅仅是浅层的。我们的口号是 “把JavaScript进行到底!”,现在无论是 ReactNative的移动端开发,还是NodeJS的后端开发,前端工程师可以做的工作早已不仅仅是局限于web页面,它已经渗透到了互联网应用层面的方方面面,或许,叫 全栈工程师 更为贴切吧。
【相关推荐】
1. 免费js在线视频教程
3. php.cn独孤九贱(3)-JavaScript视频教程
The above is the detailed content of Share an example tutorial on the implementation principle of the image upload component (React + Node). 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



How to build a real-time chat application using React and WebSocket Introduction: With the rapid development of the Internet, real-time communication has attracted more and more attention. Live chat apps have become an integral part of modern social and work life. This article will introduce how to build a simple real-time chat application using React and WebSocket, and provide specific code examples. 1. Technical preparation Before starting to build a real-time chat application, we need to prepare the following technologies and tools: React: one for building

React front-end and back-end separation guide: How to achieve front-end and back-end decoupling and independent deployment, specific code examples are required In today's web development environment, front-end and back-end separation has become a trend. By separating front-end and back-end code, development work can be made more flexible, efficient, and facilitate team collaboration. This article will introduce how to use React to achieve front-end and back-end separation, thereby achieving the goals of decoupling and independent deployment. First, we need to understand what front-end and back-end separation is. In the traditional web development model, the front-end and back-end are coupled

How to use React and Flask to build simple and easy-to-use web applications Introduction: With the development of the Internet, the needs of web applications are becoming more and more diverse and complex. In order to meet user requirements for ease of use and performance, it is becoming increasingly important to use modern technology stacks to build network applications. React and Flask are two very popular frameworks for front-end and back-end development, and they work well together to build simple and easy-to-use web applications. This article will detail how to leverage React and Flask

How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

How to use React and Google BigQuery to build fast data analysis applications Introduction: In today's era of information explosion, data analysis has become an indispensable link in various industries. Among them, building fast and efficient data analysis applications has become the goal pursued by many companies and individuals. This article will introduce how to use React and Google BigQuery to build a fast data analysis application, and provide detailed code examples. 1. Overview React is a tool for building

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

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
