引用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再轉換成中文,最終通過彈框顯示到瀏覽器中。