MVC 通過ajaxSubmit上傳圖片並顯示

js代碼
function submitform() {
        $("#form_upload").ajaxSubmit({
            success: showResponse
        });
    }

    function showResponse(responseText) {
        if (responseText != null) {
            alert('上傳成功!');
        } else {
            alert('操作失敗!');
        }
    }

    $(function () {
        $("#upImg").on("change", function () {
            var file = this.files[0];

            if (this.files && file) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('#result').attr('src', e.target.result);
                }
                reader.readAsDataURL(file);
            }
        });
    })
前臺代碼
<table>
                <tr>
                    <td style="padding-top:20px;">生產(經營)許可證證件照片</td>
                    <td>
                        <form id="form_upload" style="height:4px;" action="Upload" target="iframeInfo" method="post" enctype="multipart/form-data">
                            <input name="upImg" id="upImg" type="file" />
                            <input type="submit" value="上傳" />
                        </form>                        
                    </td>
                </tr>
                <tr>
                    <td>
                        <img id="result" style="width:200px;height:200px;" src="" alt="">
                    </td>
                    <td>
                        <iframe name="iframeInfo" id="iframeInfo" style="border:0px;"></iframe>
                    </td>
                </tr>
            </table>
            
 (這裏添加iframe,因爲後臺返回時會跳轉,把form放入iframe裏提交就不會跳轉頁面)
後臺代碼 
[HttpPost]        
        public ActionResult Upload(HttpPostedFileBase upImg)
        {
            if (upImg == null)
            {
                return Content("文件上傳錯誤,請重新選擇文件!");

            }
            string fileName = System.IO.Path.GetFileName(upImg.FileName);
            string filePhysicalPath = Server.MapPath("~/credimages/" + fileName);
            try
            {
                upImg.SaveAs(filePhysicalPath);
                Session["ImgPath"] = filePhysicalPath;
                return Content("上傳成功");
            }
            catch
            {
                return Content("上傳異常 !");

            }
        }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章