In node. js, we can use the formidable module to easily implement the file upload function, the code is as follows:
varQ = require (' q '));varUtil = require (' util '));varFS = require (' FS ');varPath = require (' path ');varmoment = require (' moment '));varFormidable = require (' formidable '));varImageupload =function() {};imageupload.prototype.useformparsecallback=function(req) {varDeferred =Q.defer (); varform =NewFormidable. Incomingform (); Form.parse (req, deferred.makenoderesolver ()); returndeferred.promise;};//ensure that the directory exists//created synchronously (multiple times) if the specified directory does not existImageUpload.prototype.ensureUploadPathExist =function(Uploadpath, mode) {if(!Fs.existssync (Uploadpath)) { varpathtmp; Uploadpath.split (PATH.SEP). ForEach (function(dirname) {if(pathtmp) {pathtmp=Path.join (pathtmp, dirname); } Else{pathtmp=dirname; } if(!Fs.existssync (pathtmp)) { if(!Fs.mkdirsync (pathtmp, mode)) { return false; } } }); } return true;}; ImageUpload.prototype.uploadImage=function(req) {varPathName = '/uploadimgs/'; varUploadpath = Path.join (__dirname, ' ... /.. /public ', PathName); This. Ensureuploadpathexist (Uploadpath); return This. Useformparsecallback (req). Then (function(files) {varFile = Files[1].imagefile; varFileType = File.type.split ('/') [1]; varNewFileName = ' Upload_ ' + Moment (). Format (' x ') + math.random (). toString (). substr (2, 10) + '. ' +FileType; Fs.renamesync (File.path, Uploadpath+newfilename); returnPathName +NewFileName; });}; Module.exports= Imageupload;
Module Q is used in the preceding code to handle callback processing in node. js, and for how to use Q You can search your own Baidu and don't repeat it here. The function ensureuploadpathexist () ensures that the destination directory where the file is uploaded is present and will be created if it does not exist. The file is uploaded in the/public/uploadimgs/directory, and is renamed in the specified format to prevent the file from being overwritten, and the call to the Fs.renamesync () function is in place of the problem. Under normal circumstances, if the uploaded directory is local, it is not problematic to perform the Fs.renamesync () function renaming the file, but if it is a cross-partition rename, such as using NFS in Linux Or a shared directory, the permissions errors that cross-partition renaming are reported here. The workaround is to replace the Fs.renamesync () function with the following code:
var readstream = fs.createreadstream (file.path); var writestream = Fs.createwritestream (Uploadpath +var deferred = q.defer (); Util.pump ( Readstream, Writestream, Deferred.makenoderesolver ()); return deferred.promise.then (function() { fs.unlinksync (file.path); return pathName + NewFileName;});
The above code can be used to upload local files, or cross-partition file uploads can be implemented.
node. JS uses Fs.renamesync report Cross-device link not permitted error