Koa2 makes file upload and download function
This time I will bring you Koa2 implementation File uploaddetailed download steps, what are the notes for Koa2 implementation of 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.
// 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'); })
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)
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 = '上传成功'; })
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.
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); })
There are two methods for downloading on the front end: window.open and form submission. The simpler window.open is used here.
<button onclick="handleClick()">立即下载</button> <script> const handleClick = () => { window.open('/download/1.png'); } </script>
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.
<button onclick="handleClick()">立即下载</button> <iframe name="myIframe" style="display:none"></iframe> <script> const handleClick = () => { window.open('/download/1.png', 'myIframe'); } </script>
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.
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); })
If you package the entire folder directly, you do not need to traverse each file and append it to the compressed package.
const zipStream = fs.createWriteStream('1.zip'); const zip = archiver('zip'); zip.pipe(zipStream); // 添加整个文件夹到压缩包 zip.directory('upload/'); zip.finalize();
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.
ctx.attachment(decodeURI(path)); await send(ctx, path);
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():
// koa-send path = decode(path) function decode (path) { try { return decodeURIComponent(path) } catch (err) { return -1 } }
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.
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); })
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:
What functions does new() implement in JS
What are the confusion points when using JS
The above is the detailed content of Koa2 makes file upload and download function. 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

There will be many AI creation functions in the Doubao app, so what functions does the Doubao app have? Users can use this software to create paintings, chat with AI, generate articles for users, help everyone search for songs, etc. This function introduction of the Doubao app can tell you the specific operation method. The specific content is below, so take a look! What functions does the Doubao app have? Answer: You can draw, chat, write articles, and find songs. Function introduction: 1. Question query: You can use AI to find answers to questions faster, and you can ask any kind of questions. 2. Picture generation: AI can be used to create different pictures for everyone. You only need to tell everyone the general requirements. 3. AI chat: can create an AI that can chat for users,

Both vivox100s and x100 mobile phones are representative models in vivo's mobile phone product line. They respectively represent vivo's high-end technology level in different time periods. Therefore, the two mobile phones have certain differences in design, performance and functions. This article will conduct a detailed comparison between these two mobile phones in terms of performance comparison and function analysis to help consumers better choose the mobile phone that suits them. First, let’s look at the performance comparison between vivox100s and x100. vivox100s is equipped with the latest

JPA and MyBatis: Function and Performance Comparative Analysis Introduction: In Java development, the persistence framework plays a very important role. Common persistence frameworks include JPA (JavaPersistenceAPI) and MyBatis. This article will conduct a comparative analysis of the functions and performance of the two frameworks and provide specific code examples. 1. Function comparison: JPA: JPA is part of JavaEE and provides an object-oriented data persistence solution. It is passed annotation or X

With the rapid development of the Internet, the concept of self-media has become deeply rooted in people's hearts. So, what exactly is self-media? What are its main features and functions? Next, we will explore these issues one by one. 1. What exactly is self-media? We-media, as the name suggests, means you are the media. It refers to an information carrier through which individuals or teams can independently create, edit, publish and disseminate content through the Internet platform. Different from traditional media, such as newspapers, television, radio, etc., self-media is more interactive and personalized, allowing everyone to become a producer and disseminator of information. 2. What are the main features and functions of self-media? 1. Low threshold: The rise of self-media has lowered the threshold for entering the media industry. Cumbersome equipment and professional teams are no longer needed.

What does a Bluetooth adapter do? With the continuous development of science and technology, wireless communication technology has also been rapidly developed and popularized. Among them, Bluetooth technology, as a short-distance wireless communication technology, is widely used in data transmission and connection between various devices. The Bluetooth adapter plays a vital role as an important device that supports Bluetooth communication. A Bluetooth adapter is a device that can turn a non-Bluetooth device into a device that supports Bluetooth communication. It realizes wireless connection and data transmission between devices by converting wireless signals into Bluetooth signals. Bluetooth adapter

As Xiaohongshu becomes popular among young people, more and more people are beginning to use this platform to share various aspects of their experiences and life insights. How to effectively manage multiple Xiaohongshu accounts has become a key issue. In this article, we will discuss some of the features of Xiaohongshu account management software and explore how to better manage your Xiaohongshu account. As social media grows, many people find themselves needing to manage multiple social accounts. This is also a challenge for Xiaohongshu users. Some Xiaohongshu account management software can help users manage multiple accounts more easily, including automatic content publishing, scheduled publishing, data analysis and other functions. Through these tools, users can manage their accounts more efficiently and increase their account exposure and attention. In addition, Xiaohongshu account management software has

PHP Tips: Quickly implement the function of returning to the previous page. In web development, we often encounter the need to implement the function of returning to the previous page. Such operations can improve the user experience and make it easier for users to navigate between web pages. In PHP, we can achieve this function through some simple code. This article will introduce how to quickly implement the function of returning to the previous page and provide specific PHP code examples. In PHP, we can use $_SERVER['HTTP_REFERER'] to get the URL of the previous page

"Exploring Discuz: Definition, Functions and Code Examples" With the rapid development of the Internet, community forums have become an important platform for people to obtain information and exchange opinions. Among the many community forum systems, Discuz, as a well-known open source forum software in China, is favored by the majority of website developers and administrators. So, what is Discuz? What functions does it have, and how can it help our website? This article will introduce Discuz in detail and attach specific code examples to help readers learn more about it.
