How to use form-data format to transfer files in NodeJs
这篇文章主要介绍了NodeJs form-data格式传输文件的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
本文介绍了Node Js 使用KOA处理form-data格式传输过来的文件,分享给大家。具体如下:
使用koa有一段时间了,评价是小巧精悍,只封装了基本的如request对象和response对象到上下文中,其他功能基本上靠第三方中间件来实现。导致的问题是使用起来就不太方便了,比如用koa上传文件,网上资料有限,对于小白而言,文件上传操作就困难多了。
form表单上传文件流程(PHP和node js)
文件上传操作原理
form表单【注意:enctype=”multipart/form-data”】上传文件时,首先会将文件上传到你本机的temp目录,然后执行move_upload_file(tmpfile,newfile);然后node会不会是这样呢?答案是确定的,上传文件大家都是一样的思路。
//var tmpath = path.join(os.tmpdir(), '1.txt');//模拟上传到临时目录的文件 //console.log(tmpath); //var ext = ".txt";//上传后生成文件的后缀,一般和上传的文件后缀一致 //var ph = path.join('public/upload', Date.parse(new Date()).toString() + ext);//生成新的上传文件路径全称 //console.log(ph); //var stream = fs.createWriteStream(ph);//创建一个可写流 //fs.createReadStream(tmpath).pipe(stream);//可读流通过管道写入可写流
然后分析了下上面代码:
fs.createWriteStream(path.join(os.tmpdir(), Math.random().toString()));
这里创建一个可写的流对象,即创建一个表单上传后移动到新目录的空文件;而os.tmpDir()刚好是本机临时目录,上面代码表示在临时目录下生成一个随机数空文件;
part.pipe(stream);
上面的代码表示将可读流对象内容写入到可写的流对象,即上面生成的临时文件下的文件;part是将request里面的文件对象解析成可读流。
然后koa文件上传原理就清楚了。通过表单上传文件,文件默认会存放到本机临时目录下生成一个临时文件。然后通过流的形式,打开这个临时文件将数据写入到一个新地址的可写文件流里面,前提是要提前创建这个空的可写流文件,即我们上传目标文件。
KOA2解析传输过来的post form-data信息
const Koa = require('koa'); const app = new Koa(); const bodyParser = require('koa-bodyparser'); const koaBody = require('koa-body'); const router = require('./router'); // 输出请求路径,每次请求都会输出 app.use(async (ctx, next) => { console.log(`Process ${ctx.request.method} ${ctx.request.url}...`); await next(); }); // 文件上传,注意书写的位置很重要,否则无法上传 app.use(koaBody({ multipart: true })); // 解析请求体 app.use(bodyParser()); // 使用路由 app.use(router()); app.listen(3000); console.log('app started at port 3000...');
总结一下的话,就是前端用form传递文件,bodyParse解析出这个form,对应的字段是ctx.request.body.files.字段名称(eg: abc),最后通过拷贝临时的数据文件来达到上传存储的目的。
bodyParse解析出的格式:
{ fields: { aaa: '123345' }, //Text类型的解析到fields中 files: //File类型的解析到files中 { abc: File { domain: null, _events: {}, _eventsCount: 0, _maxListeners: undefined, size: 12525, path: 'C:\\Users\\DANNYJ~1\\AppData\\Local\\Temp\\upload_d896dcc755fcd36156c6814aafb7685e', name: 'bamboo5.png', type: 'image/png', hash: null, lastModifiedDate: 2017-12-08T10:17:04.355Z, _writeStream: [Object] } } }
KOA2将POST传过来的文件存储到本地
var file = ctx.request.body.files.abc //传输文件的name是abc console.log(ctx.request.body) var tmpath= file['path']; var tmparr =file['name'].split('.'); var ext ='.'+tmparr[tmparr.length-1]; var newpath =path.join('./', parseInt(Math.random()*100) + Date.parse(new Date()).toString() + ext); console.log(tmpath); console.log(newpath); var stream = fs.createWriteStream(newpath);//创建一个可写流 fs.createReadStream(tmpath).pipe(stream);//可读流通过管道写入可写流
然后就会发现项目当前目录下面就会多出上传的文件了。
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
详细解答Webpack+Babel+React环境搭建(详细教程)
The above is the detailed content of How to use form-data format to transfer files in NodeJs. 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

How to handle file upload? The following article will introduce to you how to use express to handle file uploads in the node project. I hope it will be helpful to you!

How to delete node with nvm: 1. Download "nvm-setup.zip" and install it on the C drive; 2. Configure environment variables and check the version number through the "nvm -v" command; 3. Use the "nvm install" command Install node; 4. Delete the installed node through the "nvm uninstall" command.

This article will share with you Node's process management tool "pm2", and talk about why pm2 is needed, how to install and use pm2, I hope it will be helpful to everyone!

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

How to package nodejs executable file with pkg? The following article will introduce to you how to use pkg to package a Node project into an executable file. I hope it will be helpful to you!

npm node gyp fails because "node-gyp.js" does not match the version of "Node.js". The solution is: 1. Clear the node cache through "npm cache clean -f"; 2. Through "npm install -g n" Install the n module; 3. Install the "node v12.21.0" version through the "n v12.21.0" command.

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

How to implement OCR (optical character recognition)? The following article will introduce to you how to use node to implement OCR. I hope it will be helpful to you!
