• notice
  • Congratulations on the launch of the Sought Tech site

How to implement single file upload using node+express+axios

1. Install dependencies

Install dependencies on node server

cnpm  i multer --save

2. Backend code

var express = require( 'express' );
 var router = express.Router();

//Upload product image
var multer = require( 'multer' );
 var fs = require( 'fs' );
 var path = require( 'path' );

 //Using form upload
var upload = multer({
   storage : multer.diskStorage({
     //Set file storage location
     destination : function ( req, file, cb ) {
        let date = new Date();
        let year = date.getFullYear( );
        let month = (date.getMonth() + 1 ).toString().padStart( 2 , '0' );
        let day = date.getDate();
        //Start directly from the root directory
       let dir = ". /public/uploads/" + year + month + day;
 
       //Determine whether the directory exists, if not, create
       if (!fs.existsSync(dir)) {
         fs.mkdirSync(dir, {
           recursive : true
         });
       }
 
       //dir is the directory where the uploaded files are stored
       cb( null , dir);
     },
     //Set the file name
     filename : function ( req, file, cb ) {
        let fileName = file.fieldname + '-' + Date .now() + path.extname(file.originalname);
        //fileName is the file of the uploaded file namecb
       ( null , fileName);
     }
  })
})

    //The interface address is: admin/upload/img Write according to your own routing configuration
 router.post( '/img' ,upload.single( "imgFile" ) , function ( req,res,next ) {
     console.log(req);
    res.json({
      file : req.file
    })
 })


module .exports = router;

3. Front-end code

<template>
  <div>
        <div>
            < img :src = "url" width = "100px" >
             <!-- input type attribute is file, limit upload to file -->
            < input type = "file" @ change = "uploadImg($event)" >
        </div>
  </div>
</template>

< script > export default {
 
    data(){
        return {
             url : ''
        }
    },
    methods :{
        uploadImg(e){
            let file = e.target.files[ 0 ];
             // console.log(file);
            //limit file size
            // if(file.size > 10240){
            // alert('file size is too large');
            // }

            //limit file type
            if (!file.type.startsWith( 'image' )){
                alert( 'Only upload pictures' );
                 return
            }
            let formData = new FormData();
            formData.set( 'imgFile' ,file);
             this .$axios.post(
                 'http://127.0.0.1:3000/admin/upload/img' ,
                formData
                ).then( req => {
                     // console.log(req.data.file.path);
                    let path = req.data.file.path; //get the file path
                    // path.indexOf('\\');
                    let imgUrl = path.substring(path.indexOf( '\\' ))
                     // console.log(imgUrl);
                    // the image path obtained is \uploads\20201119\imgFile-1605779882999.jpg
                    this .url = ' http://127.0.0.1:3000' +imgUrl; //We finally need to get the picture on the server side, and we need to splicing the address of our own server
                })
        }
    }
}
</script>

< style >

</style>



Tags

Technical otaku

Sought technology together

Related Topic

0 Comments

Leave a Reply

+