Upload files using Node. js

Source: Internet
Author: User
This article mainly introduces Node. js implements file upload related information, which is very good and has reference value. If you need it, you can refer to the requirements you have encountered at work. You need to use nodejs to upload files, previously, I only knew how to upload files through a browser. Using nodejs is equivalent to simulating browser behavior. After google's experience, I realized that the browser simply uses the http protocol to transmit data to the server. The specific protocol is RFC 1867-Form-based File Upload in HTML. this protocol is used to upload files through form in a browser. First, we can see what data the browser has sent to the server, and then implement the upload function based on Huludao. We should be familiar with using form to upload files:

 


When submitting a request, you can use fiddler to capture the packet and view the data sent to the server:

POST http://www.qq.com/HTTP/1.1
Host: www.qq.com
Content-Length: 23
Content-Type: application/x-www-form-urlencoded; charset = UTF-8

Text1 = hello & text2 = world

It is worth noting that Content-Type is application/x-www-form-urlencoded by default, so the message will be URL encoded. For example, "hello" will be encoded as % E4 % BD % A0 % E5 % A5 % BD.

Next, let's take a look at how the form is uploaded. Everyone should be familiar:

 


Create a new upload.txt text file that only uses the hello worldpattern and upload it. Then we can use fiddler to capture the package, it can be found that the data sent in the past is a little more complicated (many other unrelated request lines have been removed, such as Cache Control and cookie ):

POST http://www.qq.com/HTTP/1.1
Host: www.qq.com
Content-Length: 199
Content-Type: multipart/form-data; boundary = ---- webkitformboundarywr3x7sxbyqq4zf5 g

------ Webkitformboundarywr3x7sxbyqq4zf5 g
Content-Disposition: form-data; name = "myfile"; filename = "upload.txt"
Content-Type: text/plain

Hello world

------ Webkitformboundarywr3x7sxbyqq4zf5 g --

According to the definition in RFC 1867, We need to generate a piece of boundary data, which cannot appear elsewhere in the content. This can be defined by ourselves. The algorithm generated in each browser may be different, the preceding boundary separates data. After the data is generated, you can place the separated Data in the Content-Type header and send it to the server, that is, the Content-Type in the preceding section: multipart/form-data; boundary = ---- webkitformboundarywr3x7sxbyqq4zf5 G. In addition, the uploaded content must be separated into several segments by separated data, and each segment contains the file name, there is also the name during the upload. The server uses this name to receive files and the file Type Content-Type. In this example, It is text/plain, if the uploaded png image is image/png. A blank line of the file type is the content of the uploaded file. In this example, the content is displayed directly because the uploaded text file is easy to understand, if the uploaded image file is a binary file, fiddler displays garbled characters. After the file content ends, it is a blank line plus the boundary data.

After learning about the details of the sending format, the next step is to use nodejs for programming. Simply put, you just need to send the data to the server according to the format.

Const http = require ('http'); const fs = require ('fs'); // The post address is a php for local service, used to test whether the upload is successful. var options = {hostname: 'localhost', port: 80, path: '/get. php ', method: 'post'} // generate the separated Data var boundaryKey =' ---- WebKitFormBoundaryjLVkbqXtIi0YGpaB '; // read the file content to be uploaded fs. readFile ('. /upload.txt ', function (err, data) {// assemble and separate the data segment var payload =' -- '+ boundaryKey +' \ r \ n' + 'content-Disposition: form-data; name = "myfile"; filename = "upload.txt" \ r \ n' + 'content-Type: text/plain \ r \ n \ r \ n '; payload + = data; payload + = '\ r \ n --' + boundaryKey + '--'; // send the request var req = http. request (options, function (res) {res. setEncoding ('utf8'); res. on ('data', function (chunk) {console. log ('body: '+ chunk) ;}); req. on ('error', function (e) {console. error ("error:" + e) ;}); // write boundary, the data size to be sent, and the data itself into the request req. setHeader ('content-type', 'multipart/form-data; boundary = '+ boundaryKey + ''); req. setHeader ('content-length', Buffer. byteLength (payload, 'utf8'); req. write (payload); req. end ();});


This article focuses on understanding the protocol and implementing it using code. There are many optimizations in code organization.

Finally, in local apache, simply write a php file to save the uploaded file for testing:

 


In addition, you can upload multiple files at a time according to RFC 1867. This is not detailed here. If you need it, you can refer to RFC 1867 for details.

The above section describes how to upload files in Node. js. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. I would like to thank you for your support for PHP chinnet!


For more articles related to Node. js file upload, refer to the PHP Chinese website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.