Nodejs Simple http File upload Demo

Source: Internet
Author: User
Tags http file upload

//This is a simple node HTTP that can handle the files of the current directory//and can be used to implement a special URL for testing//connect this server with http://localhost:8000 or http://127.0.0.1:8000//First, load all the modules you want to usevarHTTP = require (' http ');//HTTP Server APIvarFS = require (' FS ');//File System APIvarServer =Newhttp. Server ();//Create a new HTTP servervarPort = 8000; Server.listen (port); //run it on port 8000 hurtvarLog = require (' Util '). Log;log (' Http Server is listening ' + port + ' port '.);//node registers an event handler with the ' on ' method//when the server receives a new request, it runs the function to handle itServer.on (' request ',function(Request, response) {varfilename =NULL; //URL to parse request    varurl = require (' URL ')). Parse (Request.url); Switch(url.pathname) { Case'/upload ':        var_filename = request.headers[' File-name '];        Log (_filename); Request.once (' Data ',function(data) {//Large File//var fis = fs.createwritestream ('/txt.txt ');//fis.write (data);//fis.end ();Fs.writefile (_filename, data);        Response.End ();        });  Break;  Case'/' | | '/index.html ': FileName= ' index.html '; default: FileName= FileName | | Url.pathname.substring (1);//Remove the leading '/'        //speculate on content types based on their extension        varType = (function(_type) {Switch(_type) {//Extended Name             Case' HTML ':             Case' htm ':return' Text/html; Charset=utf-8 ';  Case' JS ':return' Application/javascript; Charset=utf-8 ';  Case' CSS ':return' Text/css; Charset=utf-8 ';  Case' TXT ':return' Text/plain; Charset=utf-8 ';  Case' Manifest ':return' Text/cache-manifest; Charset=utf-8 '; default:return' Application/octet-stream '; }} (Filename.substring (Filename.lastindexof (‘.‘) + 1))); //asynchronously reads the file and passes the content back to the callback function as a separate block of data        //for really large files, using API Fs.createreadstream () is betterFs.readfile (filename,function(err, content) {if(ERR) {//If the file cannot be read for some reasonResponse.writehead (404, {' Content-type ': ' Text/plain; Charset=utf-8 ')});            Response.Write (Err.message); } Else{//otherwise the read file succeedsResponse.writehead ($, {' Content-type '): type}); Response.Write (content); //the content of the file as the response body} response.end ();            }); }});

Index.html

<HTML><Head><title>File test</title><Script>window.onload=function(){    varFiles=document.getElementsByTagName ('input'), Len=files.length, file;  for (varI= 0; I<Len; I++) {file=Files[i]; if(File.type!== 'file') Continue; //A control that is not a file type skipsFile.onchange= function() {            var_files=  This. Files; if (!_files.length)return; if(_files.length=== 1) { //Select a single file                varXHR= NewXMLHttpRequest (); Xhr.open ('POST', 'Http://localhost:8000/upload'); varFilePath=files[0].value; Xhr.setrequestheader ('File-name', Filepath.substring (Filepath.lastindexof ('\\') + 1)); Xhr.send (_files[0]); } Else { }        }; }};</Script></Head><Body>    <inputtype= "File" /></Body></HTML>

Visit http://localhost:8000/

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.