search
HomeWeb Front-endJS TutorialHow to transfer files in NodeJs form-data format

How to transfer files in NodeJs form-data format

Jun 30, 2018 am 11:33 AM
form-datanode

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注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!

Statement
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
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software