vue+node+axios实现文件上传

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011724770/article/details/82871991

百度了很多东西,有点绕,不废话,直接上代码

html部分代码:

<div id="app">
        <input type="file" name="file" @change="changeFile" /><br />
        <button @click="sendAjax">发送请求</button><br />
        <p>已经上传{{rate}}%</p>
    </div>

vue部分代码:

var app=new Vue({
            el:'#app',
            data:{
                file:{},
                rate:0
            },
            methods:{
                sendAjax:function () {
                    
                },
                changeFile:function (e) {
                    this.file=e.target.files[0];
                },
                cancle:function () {

                }
            }
        });

axios部分代码:

sendAjax:function () {
    var fd=new FormData();      //创建form对象
    fd.append("file",this.file);        //通过append向form对象添加数据
    axios.post("http://127.0.0.1/addGoods2",fd,{
    onUploadProgress: (progressEvent) => {      //这里要用箭头函数
         //不然这个this的指向会有问题
         this.rate=parseInt( (  progressEvent.loaded/progressEvent.total  ) * 100 );
    }
    });
},

nodejs部分代码:

app.post("/addGoods2",upload.single("file"),function(req,res){
    var fileName="";
    console.log(req);
    if(req.file!=undefined){
        fileName=new Date().getTime()+"_"+req.file.originalname;
        fs.renameSync(req.file.path,__dirname+fileUploadPath+"/"+fileName);      //重命名,加后缀,不然图片会显示乱码,打不开
    }
    res.send("1");
});

这里,需要引入express,和multer模块

OK啦,需要注释的地方都写了注释~

猜你喜欢

转载自blog.csdn.net/u011724770/article/details/82871991