Vue.js 上传文件(后台使用.net)

页面部分

<div id="app">
    <form id="myform">
        <input type="file" name="fileup" id="fileup" v-on:change="fileChange($event)" />
    </form>

    <br />
    {{img}}
</div>
<script type="text/javascript">

    var app = new Vue({
        el: "#app",
        data: {
            img:""
        },
        methods: {
            fileChange: function (el) {
                if (!el.target.files[0].size) return;

                var obj = new FormData(document.getElementById("myform"));
                obj.append("name", "wzh");
                var _this = this;
                $.ajax({
                    type: 'post',
                    url: '/home/ajax',
                    data: obj,
                    cache: false,
                    processData: false, // 不处理发送的数据,因为data值是Formdata对象,不需要对数据做处理
                    contentType: false, // 不设置Content-type请求头
                    success: function (res) {
                        var arr=res.split(':');
                        if(arr[0]=="ok"){
                            _this.img=arr[1];
                        }else{
                        alert(arr[1]);
                        }
                    },
                });
            },
        }
    })
</script> 

 Controller

public ActionResult ajax()
        {
                try
                {
                    HttpPostedFileBase uploadfile = Request.Files["fileup"];
                    if (uploadfile == null)
                    {
                        return Content("no:非法上传");
                    }
                    if (uploadfile.FileName == "")
                    {
                        return Content("no:请选择文件");
                    }

                    string fileExt = Path.GetExtension(uploadfile.FileName);
                    StringBuilder sbtime = new StringBuilder();
                    sbtime.Append(DateTime.Now.Year).Append(DateTime.Now.Month).Append(DateTime.Now.Day).Append(DateTime.Now.Hour).Append(DateTime.Now.Minute).Append(DateTime.Now.Second);
                    string dir = "/UploadFile/" + sbtime.ToString() + fileExt;
                    string realfilepath = Request.MapPath(dir);
                    string readDir = Path.GetDirectoryName(realfilepath);
                    if (!Directory.Exists(readDir))
                        Directory.CreateDirectory(readDir);

                    uploadfile.SaveAs(realfilepath);
                    return Content("ok:" + dir);
                }
                catch (Exception ex)
                {
                    return Content("no:" + ex.Message);
                }
        }

 

转载于:https://www.cnblogs.com/lunawzh/p/7520304.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值