Node Note-Pray Lin

Upload files using formidable

const http = require('http'); const formidable = require('formidable'); // const fs = require('fs') const path = require('path') const sd = require("silly-datetime"); const server = http.createServer((req, res) => { if (req.url === '/api/upload' && req.method.toLowerCase() === 'post') { // parse a file upload const form = formidable({ multiples: true }); // Set the folder where the uploaded files are stored. The default folder is a temporary folder. Form.parse form.parse(req, (err, fields, // fields form data files.name files.age files.xxxxx // files single file is an object, multiple files are an array, name is the value of name on the input tag // Let oldPath = __dirname + '/' + files.multiplefiles. path // __dirname is the directory name of the current module let now = sd.format(new Date(), 'YYYYMMDDHHmmss') let ran = parseInt((Math.random() * 10000).toFixed(0)); let extname = path.extname(files.multipleFiles.name) let newPath = __dirname + '/images/' + now + ran + extname // Fs. rename asynchronously renames the oldPath file to the pathname provided by newPath. If newPath already exists, it is overwritten. There are no parameters to complete the callback except for possible exceptions. Fs.rename (oldPath, newPath, err => {if (err) throw err console.log(' rename done ')}) res.writehead (200, {'content-type': 'application/json' }); res.end(JSON.stringify({ fields, files }, null, 2)); }); return; } // show a file upload form res.writeHead(200, { 'content-type': 'text/html' }); res.end(` <h2>With Node.js <code>"http"</code> module</h2> <form action="/api/upload" enctype="multipart/form-data" method="post"> <div>Text field title: <input type="text" name="title" /></div> <div>File: <input type="file" name="multipleFiles" multiple="multiple" /></div> <input type="submit" value="Upload" /> </form> `); }); server.listen(8080, () => { console.log('Server listening on http://localhost:8080/ ... '); });Copy the code