Upload with Express 4 implementation file

Source: Internet
Author: User
Tags parse error

using Modules node-multiparty implementing file uploads

Because the Express 4 and express 3 in the use of middleware is very different: many of the previously built-in Express 3 middleware, now need to be downloaded through NPM, operation. Today I just ran into a middleware to modify the file upload function. So abandoned the original Bodyparser middleware, on GitHub found the node-multiparty module, followed by the API to do a small example, to share to everyone.

First look at the client code

<!DOCTYPE HTML><HTML><Head>    <title>Uploading files to the server</title>    <MetaCharSet= "Utf-8">    <Script>        functionUploadFile () {varFormData= NewFormData (); varFiles=document.getElementById ('file'). files; varfile=files[0]; Formdata.append ('myfile', file); varXHR= NewXMLHttpRequest (); Xhr.open ('POST', 'index.html', true); Xhr.onload= function(e) {if ( This. Status==  $) {document.getElementById ('result'). InnerHTML=  This. Response;            }            };        Xhr.send (FormData); }    </Script></Head><Body><H1>Uploading files using Bodyparser middleware</H1><formID= ' Form1 'enctype= "Multipart/form-data">Please select a file<inputtype= "File"ID= "File"name= "File"><BR>    <inputtype= "button"value= "Upload file"onclick= "UploadFile ();"><BR></form><OutputID= "Result"></Output></Body></HTML>

The service-side code is as follows:

varExpress = require (' Express ');varFS = require (' FS ');varMultiparty = require (' multiparty '));varApp =Express (); App.get ('/index.html ',function(req, res) {Res.sendfile (__dirname+ '/index.html ');}); App.post ('/index.html ',function(req, res) {varform =NewMultiparty. Form ({uploaddir: './public ')}); Form.on (' Error ',function(Err) {Console.log (' Error parsing form: ' +err.stack);    }); Form.parse (req,function(Err, fields, files) {varfilestmp = json.stringify (Files,NULL, 2); if(Err) {Console.log (' Parse Error: ' +err); Res.send ("The Write file operation failed. "); }Else{res.send ("File Upload succeeded"); Console.log (' Parse files: ' +filestmp); varFilenamearr =Object.keys (files); varFirstfilename = filenamearr[0]; varFiledataarr =Files[firstfilename]; Console.log (typeofFiledataarr);            Console.log (Filedataarr); varFileData = filedataarr[0]; varUploadedpath =Filedata.path; varDstpath = './public/' +Filedata.originalfilename; Fs.rename (Uploadedpath, Dstpath,function(err) {if(Err) {Console.log ("Renaming file Error:" +err); } Else{Console.log ("Rename file succeeded. ");        }            }); }    });}); App.listen (1337, ' 127.0.0.1 ');

Start Server: Node App.js

In the browser enter: http://localhost:1337/index.html, you will see the following interface

Click to select any file and then click Upload File and you will see the files in the public folder under your items directory more than the one you just uploaded.

Alternatively, you can also use multer module for file upload

Upload with Express 4 implementation file

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.