Home > Web Front-end > JS Tutorial > body text

How to transfer files in NodeJs form-data format

不言
Release: 2018-06-30 11:33:35
Original
1640 people have browsed it

这篇文章主要介绍了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);//可读流通过管道写入可写流
Copy after login

然后分析了下上面代码:

fs.createWriteStream(path.join(os.tmpdir(), Math.random().toString()));
Copy after login

这里创建一个可写的流对象,即创建一个表单上传后移动到新目录的空文件;而os.tmpDir()刚好是本机临时目录,上面代码表示在临时目录下生成一个随机数空文件;

part.pipe(stream);
Copy after login

上面的代码表示将可读流对象内容写入到可写的流对象,即上面生成的临时文件下的文件;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...');
Copy after login

总结一下的话,就是前端用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] } 
   } 
}
Copy after login

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);//可读流通过管道写入可写流
Copy after login

然后就会发现项目当前目录下面就会多出上传的文件了。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

关于Nodejs服务端字符编解码和乱码的处理

node.js 利用流实现读写同步,边读边写的功能

关于nodejs socket服务端和客户端的简单通信功能

The above is the detailed content of How to transfer files in NodeJs form-data format. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!