1.前端html代码
<input style="width:100%" onchange="loadpicture(1)" type="file" name="file" id="file➩1"> <img id="pic➩1" style="width:100%;height:120px" src="/Resource/Document/NetworkDisk/ProjectActivity/590600b4-f330-43c2-96fb-ea221f9e0ce2.jpg"> <input hidden="true" id="picsrc➩1" class="txt"> <input hidden="true" id="PictureUrl➩1" class="txt">
2.js代码,使用FileReader读取文件
function loadpicture(i) { var obj = document.getElementById("file➩" + i); var file = obj.files[0]; //alert(file); //创建读取文件的对象 var reader = new FileReader(); //创建文件读取相关的变量 var imgFile; //为文件读取成功设置事件 reader.onload = function (e) { //alert('文件读取完成'); imgFile = e.target.result; //console.log(imgFile); $("#pic➩" + i).attr('src', imgFile); $("#picsrc➩" + i).val(imgFile); }; //正式读取文件 reader.readAsDataURL(file); }
3.ajax传后台,此处有封装,用GetTableDataJson的方式获取了每一个file的ID
实际传输的话只需要传
$("#picsrc➩" + i).val()的值
//保存事件 function AcceptClick() { if (!CheckDataValid('#form1')) { return false; } var ActivityForm = GetTableDataJson("#ActivityForm"); var ProblemForm = GetTableDataJson("#ProblemForm"); Loading(true, "正在提交数据..."); window.setTimeout(function () { var postData = GetWebControls("#form1"); postData["ActivityForm"] = ActivityForm; postData["ProblemForm"] = ProblemForm; postData["BuildFormJson"] = JSON.stringify(GetWebControls("#CustomAttribute")); AjaxJson("/ProjectManageModule/project/SubmitActivityForm?KeyValue=" + GetQuery('KeyValue'), postData, function (data) { tipDialog(data.Message, 3, data.Code); top.frames[tabiframeId()].windowload(); closeDialog(); }); }, 200); }
4.后台c#代码,有可能会报GDI一般性错误的报错,
我这里是一开始目录没有对,所以报错,
realPath可以用
this.Server.MapPath(VirtualPath)的方式获取
由于我这边的文件存储目录和应用目录不在同一个盘符,所以使用了直接路径的写法
#region 图片处理,采用base64的方式转码解码 string virtualPath = ""; //图片上传 if (!string.IsNullOrEmpty(entityD.picsrc)) { //删除老的图片 string FilePath = this.Server.MapPath(entityD.PictureUrl); if (System.IO.File.Exists(FilePath)) System.IO.File.Delete(FilePath); string fileGuid = CommonHelper.GetGuid; //long filesize = Filedata.ContentLength; string FileEextension = ".jpg"; string uploadDate = DateTime.Now.ToString("yyyyMMdd"); //string UserId = ManageProvider.Provider.Current().UserId; virtualPath = string.Format("~/Resource/Document/NetworkDisk/{0}/{1}{2}", "ProjectActivity", fileGuid, FileEextension); string realPath = string.Format(@"D:\LeaRun\Resource\Document\NetworkDisk\{0}\{1}{2}", "ProjectActivity", fileGuid, FileEextension); //string fullFileName = this.Server.MapPath(virtualPath); ////创建文件夹,保存文件 //realPath = Path.GetDirectoryName(fullFileName); //先处理图片文件 string temp = entityD.picsrc.Substring(23); byte[] arr2 = Convert.FromBase64String(entityD.picsrc.Substring(23)); using (MemoryStream ms2 = new MemoryStream(arr2)) { System.Drawing.Bitmap bmp2 = new System.Drawing.Bitmap(ms2); bmp2.Save(realPath, System.Drawing.Imaging.ImageFormat.Jpeg); bmp2.Dispose(); ms2.Close(); } entityD.PictureUrl = virtualPath; } #endregion