1.页面cshtml
<form name="frmInput" id="frmInput" method="post" action="@Url.Action(ViewContext.RouteData.Values["Action"].ToString())" enctype="multipart/form-data" > <div class="form-group col-md-6"> <label class="control-label col-md-4"> 图片一 </label> <div class="col-md-8 input-group"> <ul class="list-unstyled"> <li style="float: left; width: 180px;position:relative;"> <img src="@Url.Content(Model.MDetailImageUrl)" alt="图片" width="140" /> <input class="input_file" id="TDetailImageUrl" type="file" name="TDetailImageUrl" tid="5" onchange="ImagePreview(this)" /> </li> </ul> </div> </div> <div class="form-group col-md-6"> <label class="control-label col-md-4"> 图片二 </label> <div class="col-md-8 input-group"> <ul class="list-unstyled"> <li style="float: left; width: 180px;position:relative;"> <img src="@Url.Content(Model.MDetailImageUrl)" alt="图片" width="140" /> <input class="input_file" id="MDetailImageUrl" type="file" name="MDetailImageUrl" tid="6" onchange="ImagePreview(this)" /> </li> </ul> </div> </div> <input type="button" value="保存" onclick="Input.Save(this)" class="btn-8" /> </from>
2.脚本提交
路径:@Html.Hidden("ImagePreviewUrl", Url.Action("ImagePreview"))
//图片预览 function ImagePreview(e) { if ($(e).val() == "") { alert("请选择一个图片文件,再点击上传。"); return; } $(e).closest("form").ajaxSubmit({ url: $("#ImagePreviewUrl").val() + "?name=" + $(e).attr("name"), success: function (data, status) { if (status == "success" && data != "") { $(e).parent().children("img").attr("src", data); } else { alert("图片格式不对"); } } }); }
3. 控制器方法
ImagesAPPI.PreviewDataForSingle为自定义方法,返回的是base64数据
public string ImagePreview(string name) { int fileIndex = 0; string result=""; if (Request.Files.Count > 0) { for (int i = 0; i < Request.Files.Count; i++) { if (!string.IsNullOrWhiteSpace(Request.Files[i].FileName)) { string inputName = Request.Files.AllKeys[i]; if (!string.IsNullOrWhiteSpace(inputName) && name == inputName) { fileIndex = i; break; } } } result = ImagesAPPI.PreviewDataForSingle(Request.Files[fileIndex], 150, 150); } return result; }
PreviewDataForSingle静态方法
/// <summary> /// 上传图片预览 /// </summary> /// <param name="files">文件数据</param> /// <param name="width">宽度</param> /// <param name="height">高度</param> /// <returns>返回图片预览数据</returns> public static string PreviewDataForSingle(HttpPostedFileBase file, int width, int height) { if (file.ContentLength > 0 && file.ContentType.IndexOf("image/") >= 0) { return "data:image/jpeg;base64," + Convert.ToBase64String(ResizeImg(file.InputStream, width, height).GetBuffer()); } return ""; }
附:使用图片路径预览
/// <summary> /// 图片转为base64编码 /// </summary> /// <param name="Imagefilename">图片绝对路径</param> /// <returns></returns> public static string ImgToBase64String(string Imagefilename) { if(string.IsNullOrWhiteSpace(Imagefilename)) return ""; return "data:image/jpeg;base64," + Convert.ToBase64String(System.IO.File.ReadAllBytes(Imagefilename)); ; }