目的

Vue中,点击定义的组件(input type为file),选择图片并上传到后台,后台返回图片的地址,组件中接收到图片的地址,然后把图片地址从子组件中传到根组件中。

关键的两个步骤

1.第一步(发起请求上传)
前台组件代码:

       Vue.component('upload-img', {
            template: `
            <div>
                    <input type="file"   @change='upload' ref='ipt'/>

            </div>
                     `,
            methods: {
                upload: function() {
                    var that = this;
                    console.log(this.$refs.ipt);
                    console.log(this.$refs.ipt.files[0]);
                    const imgObj = this.$refs.ipt.files[0];

                    var formdata = new FormData();
                    formdata.append('avatar', imgObj);
                    $.ajax({
                        url: 'http://localhost:8888/upload',
                        type: 'post',
                        data: formdata,
                        cache: false, //缓存处理
                        contentType: false,
                        processData: false,

                        success: function(res) {
                            console.log(res);
                            console.log(res.path);
                            var imgurl = res.path;
                            that.$emit('sendurl', imgurl)
                        }

                    })
                }
            }
        })

后台代码:

const express = require('express')
const cors = require('cors')
const multer = require('multer')
const app = new express()
app.use(cors())
app.use('/uploads', express.static('uploads'))

var storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, 'uploads')
    },
    filename: function(req, file, cb) {
        cb(null, Date.now() + file.originalname)
    }
})
var upload = multer({ storage: storage })
    // 上传图片
app.post('/upload', upload.single('avatar'), function(req, res, next) {
    console.log(req.file)
    res.json({
        code: 200,
        msg: '图片上传成功',
        path: req.file.path
    })
})
app.listen('8888', () => {
    console.log('server is running at port 8888');
})

2.第二步(子组件向父组件传参数)

 <div id="app">
        <upload-img @sendurl="listenurl"></upload-img>
        <img :src="u" alt="">
    </div>
  <scritpt>
  	   var vm = new Vue({
            el: '#app',
            data: {
                u: '',
            },
            methods: {
                listenurl(url) {
                    console.log(url);
                    this.u = url;
                }
            }
        })
  </script>
Logo

前往低代码交流专区

更多推荐