image Upload
Upload and install using the multiparty plugin multiparty
npm i --save multiparty
Code implementation
const multiparty = require(‘multiparty‘);let form = new multiparty.Form({uploadDir: upload.path});
Construction parameter Description
- Encoding set receive data encoding, default is Utf-8
- Maxfieldssize limit the amount of memory that a field can allocate, default 2M
- Maxfields limits the number of fields that will be resolved before an error event is emitted, by default 1000
- Maxfilessize Limit total file size, default infinity
- Autofields enables field events and disables some of the fields ' events. If you add a field listener, it is automatically set to true.
- Autofiles enables file events and disables some of the file's events. If a file listener is added, it is set to true automatically.
- Uploaddir File Upload Directory
= = If the callback provides, Autofields and Autofiles are set to true, all fields and files are collected and passed to the callback, no longer need to listen to any form of event. ==
Event description
= = Note When you use the part event, the part event will not get data if you are listening to both fields and files. ==
More information
After adding event monitoring
let upload = uploadPath(); console.dir(upload); let form = new multiparty.Form({ uploadDir: upload.path }); form.on(‘error‘, function (err) { console.log(‘Error parsing form: ‘ + err.stack); }); form.on(‘file‘, (name, file) => { console.log(file); res.json(file); }); form.on(‘close‘, function () { console.log(‘Upload completed!‘); }); form.parse(req);
Image processing
Generally uploaded images will be processed simply, such as lossless image compression, thumbnail generation, etc.
1, using resize-img to make the installation of the components of the thumbnail
NPM Install--save resize-img
Code implementation
const resizeImg = require(‘resize-img‘); resizeImg(fs.readFileSync(file_path), {width: 800}).then(buf => { fs.writeFileSync(file_path, buf); });
2. Using Python image processing library pil Why use Python?
CPU-intensive tasks are the Achilles ' heel of node. js, and when the server performs multiple picture processing (especially for larger images), a bug occurs, so we can use the Python image processing library pil
PIL installation
pip install pillow
Python implementation
from PIL import Imageimport globimport osimport systry: im = Image.open(sys.argv[1]) o_width = im.size[0] o_height = im.size[1] thumb_width = 400 size = (thumb_width, o_height * thumb_width / o_width) im.thumbnail(size) im.save(sys.argv[2],im.format) print(sys.argv[2])except IOError: print("cannot create thumbnail for", sys.argv[1])
Node calls Pyhton
const path = require(‘path‘);const exec = require(‘child_process‘).exec;let baseDir = path.resolve(__dirname, ‘..‘);let thumb_pic = (arg1, arg2) => { return new Promise((resolve, reject) => { let py_path = baseDir + "/public/py/"; exec(`python ${py_path}thumb_pic.py ${arg1} ${arg2}`, function (error, stdout, stderr) { if (stdout.length > 0) { console.log(‘you offer args:‘, stdout); resolve(true); } else { console.log(‘you don\‘t offer args‘); resolve(false); } if (error) { console.info(‘stderr : ‘ + stderr); reject(stderr); } }); });};module.exports.thumb_pic = thumb_pic;
Here I recommend using the second method
Source Address
node. js implements picture uploads (including thumbnails)