Home Web Front-end JS Tutorial Detailed explanation of Koa2 file upload and download cases

Detailed explanation of Koa2 file upload and download cases

May 08, 2018 am 11:05 AM
koa2 Detailed explanation

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

// app.js

const koa = require('koa');

const app = new koa();

const koaBody = require('koa-body');

app.use(koaBody({

  multipart: true,

  formidable: {

    maxFileSize: 200*1024*1024 // 设置上传文件大小最大限制,默认2M

  }

}));

app.listen(3001, ()=>{

  console.log('koa is listening in 3001');

})

Copy after login

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

  1. Create a readable stream const reader = fs.createReadStream(file.path)

  2. Create a writable stream const writer = fs.createWriteStream('upload/newpath.txt')

  3. 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

const router = require('koa-router')();

const fs = require('fs');

router.post('/upload', async (ctx){

 const file = ctx.request.body.files.file; // 获取上传文件

 const reader = fs.createReadStream(file.path); // 创建可读流

 const ext = file.name.split('.').pop(); // 获取上传文件扩展名

 const upStream = fs.createWriteStream(`upload/${Math.random().toString()}.${ext}`); // 创建可写流

 reader.pipe(upStream); // 可读流通过管道写入可写流

 return ctx.body = '上传成功';

})

Copy after login

This method is suitable for uploading images, text files, compressed files, etc.

File download

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

const router = require('koa-router')();

const send = require('koa-send');

router.post('/download/:name', async (ctx){

 const name = ctx.params.name;

 const path = `upload/${name}`;

 ctx.attachment(path);

  await send(ctx, path);

})

Copy after login

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

<button onclick="handleClick()">立即下载</button>

<script>

 const handleClick = () => {

 window.open('/download/1.png');

 }

</script>

Copy after login

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

<button onclick="handleClick()">立即下载</button>

<iframe name="myIframe" style="display:none"></iframe>

<script>

 const handleClick = () => {

 window.open('/download/1.png''myIframe');

 }

</script>

Copy after login

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

const router = require('koa-router')();

const send = require('koa-send');

const archiver = require('archiver');

router.post('/downloadAll', async (ctx){

 // 将要打包的文件列表

 const list = [{name: '1.txt'},{name: '2.txt'}];

 const zipName = '1.zip';

 const zipStream = fs.createWriteStream(zipName);

  const zip = archiver('zip');

  zip.pipe(zipStream);

 for (let i = 0; i < list.length; i++) {

 // 添加单个文件到压缩包

 zip.append(fs.createReadStream(list[i].name), { name: list[i].name })

 }

 await zip.finalize();

 ctx.attachment(zipName);

 await send(ctx, zipName);

})

Copy after login

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

const zipStream = fs.createWriteStream('1.zip');

const zip = archiver('zip');

zip.pipe(zipStream);

// 添加整个文件夹到压缩包

zip.directory('upload/');

zip.finalize();

Copy after login

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

await send(ctx, path);

Copy after login

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

// koa-send

path = decode(path)

function decode (path) {

 try {

  return decodeURIComponent(path)

 catch (err) {

  return -1

 }

}

Copy after login

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

const router = require('koa-router')();

const sendfile = require('koa-sendfile');

router.post('/download/:name', async (ctx){

 const name = ctx.params.name;

 const path = `upload/${name}`;

 ctx.attachment(decodeURI(path));

  await sendfile(ctx, path);

})

Copy after login

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!

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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

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++ Detailed explanation of the mode function in C++ Nov 18, 2023 pm 03:08 PM

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 Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

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 remainder function in C++ Detailed explanation of remainder function in C++ Nov 18, 2023 pm 02:41 PM

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 Detailed explanation of the usage of Vue.nextTick function and its application in asynchronous updates Jul 26, 2023 am 08:57 AM

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

Detailed explanation of php-fpm tuning method Detailed explanation of php-fpm tuning method Jul 08, 2023 pm 04:31 PM

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

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

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 the linux system call system() function Detailed explanation of the linux system call system() function Feb 22, 2024 pm 08:21 PM

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

See all articles