上传文件前端代码如下:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 5 <title></title> 6 <meta charset="utf-8" /> 7 <script src="../js/vue.js"></script> 8 <script src="../js/vue-resource.js"></script> 9 <script src="../asset/js/jquery.js"></script> 10 11 </head> 12 <body> 13 <div id="app"> 14 <input type="file" @change="getFile($event)" /><button @click="upload">上传</button> 15 <div>{{ result }}</div> 16 <div v-show="uping==1">正在上传中</div> 17 </div> 18 19 <script> 20 new Vue({ 21 el: '#app', 22 data: { 23 upath: '', 24 result: '', 25 uping:0 26 }, 27 methods: { 28 upload: function () { 29 //console.log(this.upath); 30 var zipFormData = new FormData(); 31 zipFormData.append('filename', this.upath);//filename是键,file是值,就是要传的文件,test.zip是要传的文件名 32 let config = { headers: { 'Content-Type': 'multipart/form-data' } }; 33 this.uping = 1; 34 this.$http.post('http://localhost:42565/home/up', zipFormData,config).then(function (response) { 35 console.log(response); 36 console.log(response.data); 37 console.log(response.bodyText); 38 39 var resultobj = response.data; 40 this.uping = 0; 41 this.result = resultobj.msg; 42 }); 43 }, 44 45 getFile: function (even) { 46 this.upath = event.target.files[0]; 47 }, 48 } 49 }); 50 </script> 51 </body> 52 </html>
后端处理代码如下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); }