
File upload is probably an essential operation in every project. Today we use nodejs to implement a file upload module.
1. Module
npm i multiparty
npm i express
2.
We put the code in the ( upload.js ) file. The code in the file is as follows:
// Upload file module const multiparty = require('multiparty')
//File operation module const fs = require('fs')
//Import the express framework const express = require('express')
//Routing const router = express.Router()
// Upload file interface router.post('/upload/file', (req, res) => {
/* Generate a multiparty object and configure the upload target path */
let form = new multiparty.Form();
//Set encoding form.encoding = 'utf-8';
//Set the file storage path, using the currently edited file as a relative path form.uploadDir = './public';
// parse, form parser // fields: ordinary form data // files: uploaded file information form.parse(req, function (err, fields, files) {
try {
//The file is files.file[0]
let upfile = files.file[0]
// Name the file and modify the path in the upfile file, otherwise the file name will be randomly generated let newpath = form.uploadDir + '/' + upfile.originalFilename //File name// Rename fs.renameSync(upfile.path, newpath);
//Return information, ((upfile.size)/1048576).toFixed(2) Convert the file from B to M units and round to two decimal places. res.send({
code:200,
msg:'File Success',
file_name:upfile.originalFilename,
file_size:((upfile.size)/1048576).toFixed(2)+'M'
})
} catch {
// Message console.log(err) under abnormal circumstances
res.send({
code:401,
msg:'File error',
more_msg:err
})
}
})
})
// Export this module for calling in the main function file module.exports = router 3.main.js file
// Introduce the express module const express = require('express')
// Instantiate express
const app = express()
// Folder mapping app.use('/static',express.static('public'))
// Upload file interface const upload=require('./router/upload')
app.use(upload)
// Listening service app.listen('3333', '0.0.0.0', (res) => {
console.log('Server running http://127.0.0.1:3333')
}) 4. Example

knock off