引用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="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再转换成中文,最终通过弹框显示到浏览器中。