Detailed explanation of Koa2 file upload and download cases
This time I will bring you Koa2File uploaddetailed download case, what are the notes for Koa2 file upload and download, the following is a practical case, let’s take a look.
Preface
Uploading and downloading are relatively common in web applications, whether they are pictures or other files. In Koa, there are many middleware that can help us quickly implement functions.
File upload
When uploading files in the front-end, we upload them through forms, but the uploaded files cannot be passed through ctx like ordinary parameters on the server side. .request.body gets. We can use koa-body middleware to process fileupload, which can put the request body into ctx.request.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
After using the middleware, you can get the uploaded file content in ctx.request.body.files. What needs to be paid attention to is setting maxFileSize, otherwise an error will be reported once the uploaded file exceeds the default limit.
After receiving the file, we need to save the file to the directory and return a url to the front end. The process in node is
Create a readable stream const reader = fs.createReadStream(file.path)
Create a writable stream const writer = fs.createWriteStream('upload/newpath.txt')
The readable stream is written to the writable stream through the pipe reader.pipe(writer)
1 2 3 4 5 6 7 8 9 10 |
|
This method is suitable for uploading images, text files, compressed files, etc.
koa-send is a static file service middleware that can be used to implement the file download function.
1 2 3 4 5 6 7 8 |
|
There are two methods for downloading on the front end: window.open and form submission. The simpler window.open is used here.
1 2 3 4 5 6 |
|
The default window.open here is to open a new window, flash and then close, which does not give the user a good experience. You can add the second parameter window.open('/download/1.png ', '_self'); , so it will be downloaded directly in the current window. However, this replaces the current page with the url, which will trigger page events such as beforeunload. If your page listens to this event and performs some operations, it will have an impact. Then you can also use a hidden iframe window to achieve the same effect.
1 2 3 4 5 6 7 |
|
Batch download
There is no difference between batch download and single download, just perform a few more downloads. There is really nothing wrong with this. If you pack so many files into a compressed package and then download only this compressed package, wouldn't the experience be better?
File Packaging
archiver is a module that can realize cross-platform packaging function in Node.js, supporting zip and tar formats.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
If you package the entire folder directly, you do not need to traverse each file and append it to the compressed package.
1 2 3 4 5 6 |
|
Note: When packaging the entire folder, the generated compressed package file cannot be stored in this folder, otherwise it will be packaged continuously.
Chinese encoding issues
When the file name contains Chinese characters, some unexpected situations may occur. So when uploading, if it contains Chinese, I will encode the file name with encodeURI() to save it, and then decrypt it with decodeURI() when downloading.
1 2 |
|
ctx.attachment Set Content-Disposition to "attachment" to instruct the client to prompt for download. Use the decoded file name as the name of the downloaded file to download. In this way, when downloaded locally, the Chinese name will still be displayed.
However, in the source code of koa-send, the file path will be decoded with decodeURIComponent():
1 2 3 4 5 6 7 8 9 |
|
At this time, after decoding, download the path containing Chinese, and the path stored in our server It is an encoded path, so naturally the corresponding file cannot be found.
To solve this problem, don't let it be decoded. If you don’t want to touch the koa-send source code, you can use another middleware koa-sendfile instead.
1 2 3 4 5 6 7 8 |
|
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How to implement Observer in Vue
vue.js element-ui tree tree control how to modify iview
The above is the detailed content of Detailed explanation of Koa2 file upload and download cases. 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





Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of the mode function in C++ In statistics, the mode refers to the value that appears most frequently in a set of data. In C++ language, we can find the mode in any set of data by writing a mode function. The mode function can be implemented in many different ways, two of the commonly used methods will be introduced in detail below. The first method is to use a hash table to count the number of occurrences of each number. First, we need to define a hash table with each number as the key and the number of occurrences as the value. Then, for a given data set, we run

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of the remainder function in C++ In C++, the remainder operator (%) is used to calculate the remainder of the division of two numbers. It is a binary operator whose operands can be any integer type (including char, short, int, long, etc.) or a floating-point number type (such as float, double). The remainder operator returns a result with the same sign as the dividend. For example, for the remainder operation of integers, we can use the following code to implement: inta=10;intb=3;

Detailed explanation of the usage of Vue.nextTick function and its application in asynchronous updates. In Vue development, we often encounter situations where data needs to be updated asynchronously. For example, data needs to be updated immediately after modifying the DOM or related operations need to be performed immediately after the data is updated. The .nextTick function provided by Vue emerged to solve this type of problem. This article will introduce the usage of the Vue.nextTick function in detail, and combine it with code examples to illustrate its application in asynchronous updates. 1. Vue.nex

PHP-FPM is a commonly used PHP process manager used to provide better PHP performance and stability. However, in a high-load environment, the default configuration of PHP-FPM may not meet the needs, so we need to tune it. This article will introduce the tuning method of PHP-FPM in detail and give some code examples. 1. Increase the number of processes. By default, PHP-FPM only starts a small number of processes to handle requests. In a high-load environment, we can improve the concurrency of PHP-FPM by increasing the number of processes

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions
