Node-formidable mounting frame
Installation dependencies:
npm i -s formidable
The first step: Add a reference
let formidable = require('formidable')
Step Two: instantiating the object
let form = new formidable.IncomingForm();
Part III: file upload path settings
form.uploadDir = "./ directory file";
Part IV: Get the contents of the form
form.parse(req,(err,fields,files)=>{ res.writeHead(200,{'content-type':'text/plain'});
res.write('received upload:\n\n');
res.end(util.inspect({fields:fields,files:files})); });
Installation node-uuid generate some naming
Installation depends
npm i uuid
Quote
let uuidv1 = require('uuid/v1')
use
let name = uuidv1();
Modify uploaded over the file name
The first step: Get the file suffix
let extName = path.extname(files.photo.name);
Step 3: Set path
let oldPath = __dirname + "/" + files.photo.path;
let newPath = __dirname + "/uploads/" + name + extName;
Fourth step: rename
fs.rename(oldPath, newPath, (err)=>{ if(!err){ res.writeHead(200, {'content-type': 'text/html;charset=UTF-8'}); res.write("写入成功"); res.end(util.inspect({fields: fields, files: files})); }else { throw err; } });