Node. js simulated Browser file upload example

Source: Internet
Author: User

This article mainly introduces the implementation code of Node. js simulating Browser file upload. For more information, see

OSChina posted it, and that is mine. Now put it here. The Haha code is as follows: var path = require ("path"); var fs = require ("fs "); var http = require ("http"); // post value payload var getfield = function (field, value) {return 'content-Disposition: form-data; name = "'+ field +'" \ r \ n \ r \ n' + value + '\ r \ n';} // file payload var getfieldHead = function (field, filename) {var fileFieldHead = 'content-Disposition: form-data; name = "'+ field + '"; filename = "'+ filename +'" \ r \ n' + 'C Ontent-Type: '+ getMime (filename) +' \ r \ n \ r \ n'; return fileFieldHead;} // obtain Mime var getMime = function (filename) {var mimes = {'.png ': 'image/png', '.gif ': 'image/gif', '.jpg ': 'image/jpeg', '.jpeg ': 'image/jpeg ','. js': 'appliction/json ','. torrent ': 'application/octet-stream'}; var ext = path. extname (filename); var mime = mimes [ext]; mime = !! Mime? Mime: 'application/octet-stream'; return mime;} // obtain the boundary check random string var getBoundary = function () {var max = 9007199254740992; var dec = Math. random () * max; var hex = dec. toString (36); var boundary = hex; return boundary;} // get boundary var getBoundaryBorder = function (boundary) {return '--' + boundary + '\ r \ n';} // format the function fieldPayload (opts) {var payload = []; for (var id in opts. field) {payload. push (getfield (id, opts. field [id]);} payload. push (""); return payload. join (getBoundaryBorder (opts. boundary);} // post data function postRequest (opts) {filereadstream (opts, function (buffer) {var options = require ('url '). parse (opts. url); var Header ={}; var h = getBoundaryBorder (opts. boundary); var e = fieldPayload (opts); var a = getfieldHead (opts. param, opts. file); var d = "\ r \ n" + h; Header ["Content-Length"] = Buffer. byteLength (h + e + a + d) + buffer. length; Header ["Content-Type"] = 'multipart/form-data; boundary = '+ opts. boundary; options. headers = Header; options. method = 'post'; var req = http. request (options, function (res) {var data = ''; res. on ('data', function (chunk) {data + = chunk;}); res. on ('end', function () {console. log (res. statusCode) console. log (data) ;}); req. write (h + e + a); log. diy (h + e + a + buffer + d); req. write (buffer); req. end (d) ;}) ;}// read the file function filereadstream (opts, fn) {var readstream = fs. createReadStream (opts. file, {flags: 'R', encoding: null}); var chunks = []; var length = 0; readstream. on ('data', function (chunk) {length + = chunk. length; chunks. push (chunk) ;}); readstream. on ('end', function () {var buffer = new Buffer (length); for (var I = 0, pos = 0, size = chunks. length; I <size; I ++) {chunks [I]. copy (buffer, pos); pos + = chunks [I]. length;} fn (buffer);} // various settings var opt = {"url": "http://xxxx.xx", // url "file": "00.jpg ", // file location "param": "file", // file upload field name "field": {// other post fields "client": "1", "title ": "OK"}, "boundary": "---- WebKitFormBoundary" + getBoundary ()} postRequest (opt);/* ------ webkitformboundaryuzkmkaovuysq1dt \ r \ n Content-Disposition: form-data; name = "file"; filename = "00.jpg" \ r \ n Content-Type: application/octet-stream \ r \ n + file \ r \ n ------ WebKitFormBoundaryuzKmkAovUuYsQ1Dt \ r \ n Content-Disposition: form-data; name = "fieldName" \ r \ n + value \ r \ n ------ WebKitFormBoundaryuzKmkAovUuYsQ1Dt -- */The Standard Format "\ r \ n" indicates the actual format string, visually adjust it to make it look comfortable.

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.