Node.js Analog Browser File Upload example _javascript tips

Source: Internet
Author: User
Oschina, that's mine too, now put it here, haha

This piece of code can only upload one file at a time ~ ~
Copy Code code 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 ' + ' Content-type: ' +getmime (filename) + ' \r\n\r\n ';
return filefieldhead;
}
Get 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;
}
Get bounds 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 ';
}
Field formatting
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);
});

}
Reading files
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",//Files upload field name
' field ': {//remaining post fields
"Client": "1",
"title": "OK"
},
"Boundary": "----webkitformboundary" +getboundary ()
}

Postrequest (opt);
/*
------webkitformboundaryuzkmkaovuuysq1dt\r\n

Content-disposition:form-data; Name= "File"; Filename= "00.jpg" \ r \ n
Content-type:application/octet-stream
\ r \ n
\ r \ n +file\r\n

------webkitformboundaryuzkmkaovuuysq1dt\r\n

Content-disposition:form-data; Name= "FieldName"
\ r \ n
\ r \ n +value\r\n

------webkitformboundaryuzkmkaovuuysq1dt--
*/

The final comment is the standard format "\ r \ n" represents the actual string, in order to look comfortable, also visually adjust

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.