这篇文章主要介绍了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!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools
