vue.js上传文件到后端

本文实例为大家分享了vue.js异步上传文件的具体代码,供大家参考,具体内容如下:

1、上传文件前端代码如下:

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

  <title></title>

  <meta charset="utf-8" />

  <script src="../js/vue.js"></script>

  <script src="../js/vue-resource.js"></script>

  <script src="../asset/js/jquery.js"></script>



</head>

<body>

  <div id="app">

    <input type="file" @change="getFile($event)" /><button @click="upload">上传</button>

    <div>{{ result }}</div>

    <div v-show="uping==1">正在上传中</div>

  </div>



<script>

  new Vue({

    el: '#app',

    data: {

      upath: '',

      result: '',

      uping:0

    },

    methods: {

      upload: function () {

        //console.log(this.upath);

        var zipFormData = new FormData();

        zipFormData.append('filename', this.upath);//filename是键,file是值,就是要传的文件,test.zip是要传的文件名

        let config = { headers: { 'Content-Type': 'multipart/form-data' } };

        this.uping = 1;

        this.$http.post('http://localhost:42565/home/up', zipFormData,config).then(function (response) {

          console.log(response);

          console.log(response.data);

          console.log(response.bodyText);

           

          var resultobj = response.data;

          this.uping = 0;

          this.result = resultobj.msg;

        });

      },



      getFile: function (even) {

        this.upath = event.target.files[0];

      },

    }

  });

</script>

</body>

</html>

2、后端处理代码如下asp.net mvc的:

public ActionResult Up()

    {

      string msg = string.Empty;

      string error = string.Empty;

      string result = string.Empty;

      string filePath = string.Empty;

      string fileNewName = string.Empty;

      var files = Request.Files;

      if (files.Count > 0)

      {

        //设置文件名

        fileNewName = DateTime.Now.ToString("yyyyMMddHHmmssff") + "_" + System.IO.Path.GetFileName(files[0].FileName);

        //保存文件

        files[0].SaveAs(Server.MapPath("~/Uploads/" + fileNewName));

        Thread.Sleep(10 * 1000);

      }

      return Json(new { msg = "上传成功", newfilename = fileNewName }, JsonRequestBehavior.AllowGet);

    }

以上就是本文的全部内容,希望对大家的学习有所帮助。

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

vues

刚好遇见你

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值