nodeJs and elementUI achieve the picture

There are packaged in elementUI image upload control assembly, the assembly to make use of, the background image select request connection to upload pictures to the backend server.

In nodeJs in  multer  and FS  , the picture data and upload to rename the new folder.

step

1. Download multer

2. Introduction multer and fs
was cloudberry = require ( 'cloudberry'); 
was fs = require ( 'FS');

  

3. Create storage, stroage provides access to specific functions or session storage locally stored under the domain name, for example, you can add, modify or delete data stored items.

If you want to operate a domain name of the session storage, you can use Window.sessionStroage, if you want to operate a domain local store, you can use window.localstroage

Storage multer.diskStorage = var ({ 
    Where do you want: function (REQ, File, CB) { 
        // save path after receiving the output file (if there needs to be created) 
        CB (null, 'Upload /'); 
    }, 
    filename : function (REQ, file, cb) { 
        // save the file name to the original time stamp + file name, such as 151342376785-123.jpg 
        cb (null, Date.now () + "-" + file.originalname); 
    } 
});

  

4. Create a folder
createFolder = function var (Folder) { 
    the try { 
        // test path specified user permissions on the file or directory, we used to detect whether a file exists 
        // if the file path does not exist will throw an error "NO SUCH File or Directory" 
        FS .accessSync (folder); 
    } the catch (E) { 
        // folder does not exist, in a synchronized way to create a file directory. 
        fs.mkdirSync (Folder); 
    } 
};

5. Create the upload file path

was upload folder = ' ./upload/ ' ;
  createFolder(uploadFolder);

6. Create an object multer

was uploaded = mullet ({storage: storage});

7. The front end interface provides upload

router.post ( '/ Upload', upload.single ( 'File'), function (REQ, RES, Next) { 
    var File = req.file; 
    the console.log ( 'File Type:% s', file.mimetype) ; 
    the console.log ( 'original filename:% S', file.originalname); 
    the console.log ( 'file size:% S', file.size); 
    the console.log ( 'file path:% s', file .path); 
    // successful return received document data to the frontend 
    res.json ({res_code: '0', name: file.originalname, URL: file.path}); 
});

  

 

Guess you like

Origin www.cnblogs.com/blog-zy/p/10953630.html