AJAX 上傳圖片


引用jquery Form 插件,地址:http://jquery.malsup.com/form/

<script type="text/javascript">
    $(function () {
        $("#btn_show").bind("click", function () {
            $("#form_upload").show();
            var options = {
                success: function (responseText, statusText, xhr, $form) {
                    var picPath = responseText.message;
                    if (picPath == "") {
                        alert(responseText.message);
                    }
                    else {
                        $("#form_upload").hide();
                        alert(unescape(responseText.message.replace(/\\/g, "%")));
                        //                        $("#result").attr("src", picPath).show();
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log(textStatus);
                    console.log(errorThrown);
                }
            };

            $("#form_upload").ajaxForm(options);
        });
    });
</script>

  

<input type="button" id="btn_show" value="上傳圖片" /><br />
<form id="form_upload" style="padding:20px;display:none" action="AddPic" method="post" enctype="multipart/form-data">
<input name="upImg" style="width:350px; height:25px;" size="38" type="file" />
<input type="submit" value="上傳"/>
</form>

 

后台C#代碼:

  [HttpPost]
        public JsonResult AddPic(HttpPostedFileBase upImg)
        {
            string fileName = Path.GetFileName(upImg.FileName);
            string filePhysicalPath = Server.MapPath("~/Upload/"+fileName);

            string test = "\u56fe\u7247\u4ea0\u4f20\u6210\u529f";

            string name = "", message = "";
            byte[] bytes  = new byte[]{};
            try
            {
                upImg.SaveAs(filePhysicalPath);
                name = Path.GetFileName(fileName);
                bytes = Encoding.Unicode.GetBytes("圖片添加成功");
                for (int i = 0; i < bytes.Length; i+=2)
                {
                    message += "\\u" + bytes[i+1].ToString("x").PadLeft(2,'0')+bytes[i].ToString("x").PadRight(2,'0');
                }

            }
            catch (Exception ex)
            {
                message = ex.Message;
            }

            return  Json(new {
                name=name,
                message = message
            });
        }

  

 

后台把中文轉換成Unicode代碼,傳輸后JS腳本將Unicode再轉換成中文,最終通過彈框顯示到瀏覽器中。


免責聲明!

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



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