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);
                }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM