[Reprinted from:] https://www.jianshu.com/p/34d0e1a5ac70
Knowledge to explain
koa2 frame is a frame based middleware, i.e., need to use functions such as route (koa-router), log (koa-logger), you can find the corresponding middleware library, i.e. npm package, then app.use (...) imported.
Subject of this article: Upload Files is by reference to the corresponding intermediate to achieve.
I looked at the statistics, we found that file upload can be achieved middleware has three, one will be able to choose:
1) KOA-body
2) busboy
3) KOA-multer
differences on these three middleware can check their own online information, here I choose more pleasing to the eye koa-body, practical and simple.
Code
Step a: Download koa-body npm package
npm install koa-body –save
npm install koa-body --save |
Step two: Quote koa-body middleware koa project
|
Step 3: Use koa-body middleware, you can get files uploaded by ctx.request.files
Reminder:
The new version of the koa-body get uploaded files ctx.request.files
old version of koa-body get files uploaded by ctx.request.body.files
friends do not into the pit Kazakhstan, himself into the pit too long time.
Step four: After you get to the file by fs save the file to a specified directory server
Upload a single file:
|
Upload multiple files:
|
Front-end code
The way to the front of the code also attach the front end, to send the file to your server by submitting the form
|
Concluded
Today, when implementing file uploading in the project, also accidentally into a little pit, and why? (See above Step Three)
Much of the information on the Internet are looking to get the files uploaded by ctx.request.body.files, this is an older version of a file koa-body acquisition method, for safety reasons, a new version of koa-body uses ctx.request.files to get the file.
Conclusion on the causes, he wanted to learn to find official documents, official documents-based, supplemented by other documents, such fishes.