Implement file upload interface in KOA.JS

File upload is a basic function, almost every system, such as uploading pictures, uploading Excel et al. So how do you implement a support file uploaded in Node KOA applications? This article starts from the environment, and finally tests with Postman and an HTML page, respectively.

01 – Environmental Preparation

Of course, it is to initialize a KOA project, install KOA, Koa-router.

NPM Install Koa Koa-router

Set the image upload directory, upload the image to the specified directory, create a new public folder under the App Path, the directory structure is as follows :

KOA-UPLOAD / – APP —- Public —— UPLOADS —- Index.js – package.json
   Written Index.js 
Const Koa = Require (‘Koa’) const App = New KOA () Router.post (‘/ upload’, ctx => {ctx.body = ‘KOA UPLOAD DEMO’}) app.use (router.routes ()); app.listen (3000, () => {console.log (‘startup success ‘) Console.log (‘ http: // localhost: 3000 ‘)});

Then start to ensure that this is no problem.
  02- Using the KOA-BODY middleware to get uploaded files  
KOA-BODY support file, JSON, FORM format request body, installation of KOA-BODY

sets Koabody configuration parameters, Index. JS

Const Koa = Require (‘Koa’) Const Koabody = Require (‘KOA-BODY’) Const Path = Require (‘Path’) Const App = New Koa () app.use (koabody ({// support file format multipart: true, formidable: {// Upload directory UPLOADDIR: path.join (__ DIRNAME, ‘PUBLIC / UPLOADS’), // Reserved File Extensions Keepextensions: True, }});

...

Next, complete / upload route, get file, then return to file path directly

Router.post (‘/ upload “, ctx => {const file = ctx.request.files.file ctx.body = {path: file.path}}
   
So we actually be uploaded by file, upload the file to public / uploads, we use postman to test it.
Open Postman, type http: // localhost: 3001 / uploaD, select the POST method, and select the file with body to transfer, and select the Form-Data format, then select the file type in the key.

Then you can select the image to upload. After the upload is successful, you can see a picture under the UPLOADS folder, and output the path of the picture.
03- Using the KOA-Static middleware to generate pictures link
   The local path directly returned to the picture is actually not used, we should return an HTTP link. Image Address, click on the address to view the image. 
With the Koa-Static middleware, you can help us generate a static service, which specifies a folder, and all files under the folder can be accessed through the HTTP service.

Install:

NPM Install Koa-Static

and registered on the app, we registered him in front of the Koabody middleware, set the public as a static file directory.

在Koa.js中实现文件上传的接口功能 Const KoaStatic = Require (‘Koa-Static’) … APP.USE (KoaStatic (path.join (__ dirname, ‘public’))))))

Launcher, so that the file under public, you can use the HTTP service to open, we can open the previously uploaded image: http: // Localhost: 3001 / UPLOADS / UPLOAD_65C1D26E5A47870CF4011AAD1243FCE0.PNG can be displayed directly in your browser.

Then we transform the implementation of the UPLOAD routing, let it generate a picture link to return to the client

Router.post (‘/ upload’, ctx => {const file = ctx.request.files.file const basenaMe = path.basename (file.path) ctx.body = { “URL”: $ {ctx.origin} / uploads / $ {basename} `}})

BaseName can get files Names and extensions, CTX.origin gets the domain name of the server, that is, such as localhost: 3001, but we can’t write.
Test it with a Postman, you can see the returned picture URL, click to open it directly.
   
04- Write front page Upload file

We used Postman to simulate the upload file for testing, although it can be high efficient The backend interface we wrote, but some students in our front end may usually be more familiar with the front-end page, then we will write a table page to test.

Create an UPLOAD.html file in public as a test page.

Upload
   

This is a traditional form commit. This code in our actual work may be uncommon. Action is our submitted interface,

enctype = “multipart / form-data”

is to specify the upload file Format. Input’s Name property must be equal to File because we accept the field name is file.

Then we open this page with HTTP: http: // localhost: 3001 / upload.html, because our entire public directory is already a static HTTP service directory, all files can be accessed via HTTP. 在Koa.js中实现文件上传的接口功能

Select a file, click upload, after the upload is successful, you can see the return file address

Summary
 The above is the interface function that implements file uploads in KoA.js, I hope that if you have any questions, please leave a message if you have any questions. Xiaobian will reply to everyone in time. Thank you very much for your support of Tumi Cloud Website!  If you think this article helps you, welcome to reprint, please indicate the source, thank you!                      
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment