node. js implements picture uploads (including thumbnails)

Source: Internet
Author: User

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
    • Part is triggered when the file data is requested, and the callback function is an instance object that implements a readable stream
      • Headers: Head File
      • Name: Field names
      • FileName: File name
      • Bytefffset: The byte offset of the principal data
      • ByteCount: Total byte length of data
    • Aborted triggered when a request is aborted

    • Close triggers after the request ends

    • file receives the parameters of the files
      • Name: Field names
      • File: An object that stores information about files
      • FieldName: Field Name
      • OriginalFilename: File name
      • Path: The exact path of the file written to the disk
      • Headers: Storing head information
      • Size: File Specific size
    • Field gets the specific data for the request. callback function two parameters
      • Name: Field name
      • Value: Field value

= = 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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.