This article mainly introduces the relevant information about node. js File Upload processing, which is very good and has reference value. If you need it, you can refer to it. Go straight to the topic. Under the premise of the basic framework of Node. js web development, we will do a file upload function.
The uploaded handler is relatively simple and can be found online.
Var url = require ('url'); var exec=require('child_process'cmd.exe c; var querystring = require ('querystring '); /********************************* test the File Upload 3rd-party module * * **********************/function fileUploadForm (request, response) {response. writeHead (200, {'content-type': 'text/html'}); var body =''+''+'
'+''+''+ ''+''+''; Response. write (body); response. end ();} function fileUploadAction (request, response) {var fs = require ('fs'); var formidable = require ('formidable'); var baseUploadPath = ". /media/upload/"; var form = new formidable. incomingForm (); form. uploadDir = '. /var/tmp '; form. parse (request, function (error, fields, files) {if (! Error) {console. log (fields); var desUploadName = baseUploadPath + files. upload. name; fs. renameSync (files. upload. path, desUploadName); response. writeHead (200, {'content-type': 'text/html'}); // The response here is worth noting. the writeHead () function must be written in form. in the callback of parse (), do not display response. write ('stored ed image:
'); Response. write (''); response. end () ;}}) ;}function showUploadImage (request, response) {var fs = require ('fs'); var imageName = querystring. parse (url. parse (request. url ). query); var baseUploadPath = ". /media/upload/"; fs. readFile (baseUploadPath + imageName. name, "binary", function (error, file) {if (error) {response. writeHead (500, {"Content-Type": "text/plain"}); response. write (error + "\ n"); response. end ();} else {response. writeHead (200, {"Content-Type": "image/png"}); response. write (file, "binary"); response. end () ;}}) ;}exports. fileuploadform = fileUploadForm; exports. fileuploadaction = fileUploadAction; exports. showuploadimage = showUploadImage;
Add
handle['/fileuploadform']=handlers.fileuploadform;handle['/fileuploadaction']=handlers.fileuploadaction;handle['/showuploadimage']=handlers.showuploadimage;
Note that you cannot add
Request. setEncoding ('utf8'); // setting this may cause upload failure. This is a bug in the formidable module.
And
request.addListener("data",function(tempPostData){ postData+=tempPostData; }); request.addListener("end",function(){ route(request,response,postData,handle); });
The above is all the content of this article. I hope it will help you learn and support PHP.
For more articles about node. js file upload and processing examples, please follow the PHP Chinese network!