无刷新上传文件
這幾天做的項目用到了文件上傳,總結一下,加深一下印象吧。嘿嘿..........
1. 一個添加功能,需要上傳圖片,上代碼。
?
1 @{ 2 using (Ajax.BeginForm("Add", "PeopleManage", new AjaxOptions() { HttpMethod = "Post", OnSuccess = "afterAdd" }, 3 new { id = "AddFrm", enctype = "multipart/form-data" })) 4 { 5 // .................... 6 <tr> 7 <td>圖標地址:</td> 8 <td id="iconTd" colspan="5"> 9 <input id="iconUrl" type="text" name="IconUrl" /> 10 11 12 <input id="iconInput" type="file" name="iconImg"/> 13 <input type="button" value="上傳圖片" id="btnUploadIconImg"/> 14 15 </td> 16 </tr> 17 <tr> 18 <td> 19 圖片預覽 20 </td> 21 <td id="iconYL" colspan="5"> 22 23 </td> 24 </tr> 25 //................... 26 } 27 28 }???mvc 異步提交表單,還有文件上傳時最好加上enctype = "multipart/form-data" 這個屬性。
?2.?前端觸發事件 jquery 代碼。
??
1 //上傳圖片 2 function bindImgUploadClick() { 3 $("#btnUploadIconImg").click(function () { 4 //第一件事:判斷文件input標簽中有沒有文件 5 if ($("#iconInput").val()) { 6 //讓表單異步的提交到后臺。 7 $("#iconYL img").remove(); 8 $("#AddFrm").ajaxSubmit({ 9 error: function (error) { alert(error); }, 10 url: '/PeopleManage/UploadImage', /*設置post提交到的頁面*/ 11 type: "post", /*設置表單以post方法提交*/ 12 dataType: "text", /*設置返回值類型為文本*/ 13 success: function (data) { 14 15 $("#iconUrl").val(data); 16 $("#iconYL").append("<img id='IsUp' src='" + data + "' width='150px' heigth='80px' />"); 17 $("#iconInput").val(""); 18 } 19 }); 20 } else { 21 $.messager.alert("錯誤消息", "請選擇合法圖片!"); 22 } 23 }); 24 }?? 這是個表單整體異步提交,需要一個MyAjaxForm.js文件。 success: 是成功后,后臺返回的東東,可以返回圖片路徑,前臺展示一下縮略圖。
3. 后臺上傳的處理,代碼獻上。。
?
?
?基本就這樣勒,菜鳥一只,大家多多指教,多多交流奧 。。?? O(∩_∩)O
?
?
?
?
?
?
?
?
?
?
?
?
?
?
轉載于:https://www.cnblogs.com/dbao-8283/p/db_now.html
總結
- 上一篇: C#调用C++ DLL的方式
- 下一篇: wiki-editor语法