Nodejs implements file _ node. js for simulating form upload

Source: Internet
Author: User
Use nodejs to simulate form file upload. Multiple files can be uploaded at the same time. In the past, there was a problem with the customer in the project. My colleague said that this method has never been used. SO, it took a day to figure out this method (I think it takes a little longer) and share it with me.

Code and test cases:

Var http = require ('http'); var path = require ('path'); var fs = require ('fs'); function postFile (fileKeyValue, req) {var boundaryKey = Math. random (). toString (16); var enddata = '\ r \ n ----' + boundaryKey + '--'; var files = new Array (); for (var I = 0; I <fileKeyValue. length; I ++) {var content = "\ r \ n ----" + boundaryKey + "\ r \ n" + "Content-Type: application/octet-stream \ r \ n "+" Content-Disposition: Form-data; name = \ "" + fileKeyValue [I]. urlKey + "\"; filename = \ "" + path. basename (fileKeyValue [I]. urlValue) + "\" \ r \ n "+" Content-Transfer-Encoding: binary \ r \ n "; var contentBinary = new Buffer (content, 'utf-8'); // Chinese characters are garbled when the encoding is ascii. Files. push ({contentBinary: contentBinary, filePath: fileKeyValue [I]. urlValue});} var contentLength = 0; for (var I = 0; I <files. length; I ++) {var stat = fs. statSync (files [I]. filePath); contentLength + = files [I]. contentBinary. length; contentLength + = stat. size;} req. setHeader ('content-type', 'multipart/form-data; boundary = -- '+ boundaryKey); req. setHeader ('content-length', contentLength + Buffer. byteLength (enddata); // send the parameter var fileindex = 0; var doOneFile = function () {req. write (files [fileindex]. contentBinary); var fileStream = fs. createReadStream (files [fileindex]. filePath, {bufferSize: 4*1024}); fileStream. pipe (req, {end: false}); fileStream. on ('end', function () {fileindex ++; if (fileindex = files. length) {req. end (enddata) ;}else {doOneFile () ;}}; if (fileindex = files. length) {req. end (enddata) ;}else {doOneFile () ;}// test case // http://nodejs.org/api/http.html#http_http_request_options_callbackvar Files = [{urlKey: "file1", urlValue: "E :\\ DFBF.jpg" },{ urlKey: "file2", urlValue: "E :\\ 1.jpg "}, {urlKey: "file3", urlValue: "E: \ Pro space Chinese character"}] var options = {host: "localhost", port: "8908", method: "POST", path: "/Home/Upload"} var req = http. request (options, function (res) {console. log ("RES:" + res); console. log ('status: '+ res. statusCode); console. log ('headers: '+ JSON. stringify (res. headers); // res. setEncoding ("utf8"); res. on ("data", function (chunk) {console. log ("BODY:" + chunk) ;})) req. on ('error', function (e) {console. log ('problem with request: '+ e. message); console. log (e) ;}) postFile (files, req); console. log ("done ");

In the server test, mvc is used to write an upload method in the home controller, and upload files are traversed and saved on the hard disk.

It is only possible to upload large files. It is estimated that the server must be configured for the moment.

Server method (written under the Home Controller)

[HttpPost] public string Upload () {// HttpPostedFileBase file = this. request. files ["file"]; // file. saveAs (file. fileName); foreach (string file in this. request. files) {this. request. files [file]. saveAs (@ "E: \ New Folder \" + this. request. files [file]. fileName);} return @ "saved successfully path: E: \ New Folder \";}

Run the script:

node nodejsPostFile.js

Running result:

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.