C# 使用FileUpload控件上传图片,将文件转换成二进制进行存储与读取

状况描述:

  需要上传文件,但是不想要保存到实体路径下,便可以用该功能来实现。

效果图:

  C# 使用FileUpload控件上传图片,将文件转换成二进制进行存储与读取

  点击【Upload】按钮,上传文件到数据库;

  点击【Preview】,预览文件;

具体实现:

  前台:

 <tr>
<td class="subject" nowrap="nowrap" align="right" style="width: 180px; text-align: right;"><%=Resources.WebResource.OE_ID_TYPE%>
<!--ID Type-->
:
</td>
<td style="color: #F90;">
<asp:DropDownList ID="drpIDType_N" runat="server" style="width: 25%;" OnSelectedIndexChanged="drpIDType_N_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
<span style="color: Red;">*</span>
<asp:FileUpload ID="btnFile" runat="server" Style="width: 25%;" /> <input type="button" id="btnUpload" runat="server" value='<%$ Resources:WebResource,CC_UPLOAD%>' onserverclick="btnUpload_Click" Visible="true" style="height:inherit; text-align: center;color: #b44c00;font-weight: 700;background-color: #ffe926;" />
<a href="Javascript: void(0)" id="lnkShowImg" runat="server" title="<%$ Resources:WebResource,IMG_PREVIEW_TITLE%>" visible="false" style="width:15%"><%=Resources.WebResource.IMG_PREVIEW%></a>
</td>
</tr>
<tr>
<td class="subject" nowrap="nowrap" align="right" style="width: 180px; text-align: right;"><%=Resources.WebResource.OE_ID_NO%>
<!--ID No-->
:
</td>
<td class="name">
<input type="text" runat="server" id="txtIDNO_N" maxlength="" style="width: 96.6%;" />
<span style="color: Red">*</span>
</td>
</tr>

  后台:

 protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
UploadImg(this.btnFile, this.txtEmployeeID, this.txtDEPID);
}
catch (Exception ex)
{
ShowError("W99999", "J00006", o_PopupWin, this.mLanguage);
WriteLog(ex.ToString());
WriteLog("Browser:" + HttpContext.Current.Request.Browser.Browser);
}
} private void UploadImg(FileUpload file, string s_EmployeeID, string s_DEPID)
{
//验证文件类型
Boolean fileOK = false;
String fileExtension;
if (file.HasFile) //判断是否有图片上来了
{
fileExtension = System.IO.Path.GetExtension(file.FileName.Trim()).ToLower();//获取文件扩展名
String[] allowedExtensions = { ".jpg", ".png", ".jpeg" }; //允许上传的文件格式
for (int i = ; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
break;
}
}
}
else
{
Response.Write("<script>alert('进行提示');</script>");
return;
}
if (!fileOK)
{
Response.Write("<script>alert('进行提示');</script>");
return;
} #region 因浏览器兼容问题,会取不到文件完整路径,所以先将文件保存到本地
string strFileLocalPath = Server.MapPath("../../Upload//Tmp//");
string strFileName = strFileLocalPath + DateTime.Now.ToString("yyyyMMddHHmmss") + fileExtension;
if (Directory.Exists(strFileLocalPath) == false)
{
Directory.CreateDirectory(strFileLocalPath);
}
if (file.PostedFile.FileName.Trim() != "")
{
file.PostedFile.SaveAs(strFileName);
WriteLog("Browser:" + HttpContext.Current.Request.Browser.Browser);
}
#endregion //将文件读进二进制内存
byte[] photo = Utility.getImg(strFileName, true); //插入数据库
o_CC_Insured_BLL.insertOrUpdateCCImg(fileExtension, System.IO.Path.GetFileName(file.PostedFile.FileName), photo); //给【Preview】赋JS事件
setShowImgLink(s_EmployeeID, s_DEPID); //提示上传成功
ShowOk("W00058", "J00005", o_PopupWin, this.mLanguage);
} /// <summary>
/// 从数据库里面查询已上传的文件
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
private void setShowImgLink(string s_EmployeeID, string s_DEPID)
{
DataTable dtimg = new DataTable(); dtimg = o_CC_Insured_BLL.getUploadFileCC(s_EmployeeID, s_DEPID);
if (dtimg.Rows.Count > )
{
lnkShowImg.Attributes.Add("onclick", "funOpenShowImage('" + s_EmployeeID + "','" + s_DEPID + "');");
lnkShowImg.Visible = true;
}
else
{
lnkShowImg.Visible = false;
}
} /// <summary>
/// 将图片文件写入二进制对象
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static byte[] getImg(string filePath, bool deleteFlg)
{
//读取图片
FileStream fs = new System.IO.FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] photo;
try
{
photo = br.ReadBytes((int)fs.Length);
}
finally
{
br.Close();
fs.Close();
}
//删除文件
if (deleteFlg)
{
//删除图片文件
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
return photo;
}

  JS:

 function funOpenShowImage(s_EmployeeID, s_DEPID) {
var strUrl = "../showUploadImg.aspx";
if (document.all)//IE浏览器
{
var strParm = s_EmployeeID + "," + s_DEPID
openNewWin_IE(strUrl, strParm, , , "newwin");
}
else if ((/Trident\/\./).test(navigator.userAgent))//IE11浏览器
{
var strParm = s_EmployeeID + "," + s_DEPID
openNewWin_IE11(strUrl, strParm, , , "newwin");
}
else//其他浏览器
{
var aryParm = [["EmployeeID", s_EmployeeID], ["DEPID", s_DEPID]];
OpenNewWin(strUrl, aryParm, , , "newwin");
}
}

  预览需要新建一个页面:

  新建showUploadImg.aspx

  前台:

  添加Img控件

 <div>
<img runat="server" id="imgShow" src="\Upload\TMP\aaa.jpg" />
</div>

  后台:

 protected void Page_Load(object sender, EventArgs e)
{
try
{
clearTmp(Server.MapPath("../Upload/TMP/"));
//setInsured();
//saveImg(); string _EmployeeID = string.Empty;
string _DepID = string.Empty;
string strParm = this.Request.Form.Get("param") == null ? "" : Server.HtmlDecode(this.Request.Form.Get("param"));
if (string.IsNullOrEmpty(strParm))
{
_EmployeeID = this.Request.Form.Get("EmployeeID") == null ? "" : Server.HtmlDecode(this.Request.Form.Get("EmployeeID"));
_DepID = this.Request.Form.Get("DEPID") == null ? "" : Server.HtmlDecode(this.Request.Form.Get("DEPID"));
}
else
{
string[] arrParm = strParm.Split(',');
_EmployeeID = arrParm[] == null ? "" : arrParm[];
_DepID = arrParm[] == null ? "" : arrParm[];
} //从数据库读取文件
DataTable dtImg = new DataTable();
dtImg = o_CC_Insured_Bll.getUploadFileCC(_EmployeeID, _DepID); string strFileName = _EmployeeID + DateTime.Now.ToString("yyyyMMddhhmmss") + ".JPG";
string strPhotoPath = "../Upload/TMP/";
string strFullPhotoPath = Server.MapPath(strPhotoPath) + strFileName;
if (dtImg.Rows.Count > && dtImg.Rows[]["ImgFile"] != DBNull.Value)
{
if (Directory.Exists(Server.MapPath(strPhotoPath)) == false)
{
Directory.CreateDirectory(Server.MapPath(strPhotoPath));
}
string setImgResult = setImg((byte[])dtImg.Rows[]["ImgFile"], strFullPhotoPath);
if (string.IsNullOrEmpty(setImgResult))
{
imgShow.Src = strPhotoPath + strFileName;
}
}
}
catch
{
ShowError("W99999", "J00006", o_PopupWin, this.mLanguage);
}
} /// <summary>
/// 清空文件夹下的内容
/// </summary>
/// <param name="folderPath"></param>
public static void clearTmp(string folderPath)
{
//判斷是否有這樣的路徑
if (System.IO.Directory.Exists(folderPath) == true)
{
DirectoryInfo theFolder = new DirectoryInfo(folderPath);
FileInfo[] fileInfo = theFolder.GetFiles();
foreach (FileInfo NextFile in fileInfo) //遍历文件
{
try
{
File.Delete(NextFile.FullName);
}
catch { }
}
}
}
/// <summary>
/// 读取图片文件到指定目录
/// </summary>
/// <param name="img"></param>
/// <param name="filePath"></param>
/// <returns></returns>
public static string setImg(byte[] img, string filePath)
{
try
{
BinaryWriter bw = new BinaryWriter(File.Open(filePath, FileMode.OpenOrCreate));
bw.Write(img);
bw.Close();
return "";
}
catch (Exception ex)
{
return ex.ToString();
}
}

  JS开启新窗口的共用方法:

 //目的:提供開啟視窗的畫面
//參數:strUrl-->欲開啟畫面的網址,strParms-->參數,width-->畫面的寬度,height-->畫面的高度
// WinName-->開啟的視窗名稱
// xx. YYYY/MM/DD VER AUTHOR COMMENTS
// 1. 2016/08/22 1.00 Anne Create
function OpenNewWin(strUrl,aryParms,width,height,WinName)
{
var top=;
var left=;
if (height =='' && width==''){
width=screen.availWidth;
height=screen.availHeight;
}else if (height >screen.availHeight && width>screen.availWidth){
width=screen.availWidth;
height=screen.availHeight;
}else{
top=(screen.availHeight-height)/;
left=(screen.availWidth-width)/;
}
var newWindow = window.open("",WinName,'width='+width+'px,height='+height+'px,dependent,left='+left+',top='+top+',status=no,toolbar=false,menubar=no,scrollbars=yes,resizable=yes',true);
if (!newWindow) return false; var html ="";
//參數的處理
//var aryParm=strParms.split("&");//有多少個參數
var i=;
for(i=;i<aryParms.length;i++)
{
//var aryParaTemp = aryParm[i].split("=");//每一個參數
var aryParaTemp = aryParms[i];
html += "<input type='hidden' name='" + aryParaTemp[] + "' value='" + aryParaTemp[] + "'/>";//參數字段
}
html = "<html><head></head><body><form id='formid' method='post' action='"+strUrl+"'>"+html;
html += "</form><scr"+"ipt type='text/javascript'>document.getElementById('formid').submit()</scr"+"ipt></body></html>";
//html += "</form><script type='text/javascript'>document.getElementById('formid').submit()</script></body></html>";
newWindow.document.write(html);//提交post數據
} //目的:提供開啟視窗的畫面(跨域跳转的话,用OpenNewWin方法,IE浏览器不兼容,故重写一个)
//參數:strUrl-->欲開啟畫面的網址,strParms-->參數,width-->畫面的寬度,height-->畫面的高度
// WinName-->開啟的視窗名稱
function openNewWin_IE(strUrl,strParam,width,height,name)
{
var tempForm = document.createElement("form");
tempForm.id="tempForm1";
tempForm.method="post";
tempForm.action=strUrl;
tempForm.target=name;
var hideInput = document.createElement("input");
hideInput.type="hidden";
hideInput.name= "param"
hideInput.value= strParam;
tempForm.appendChild(hideInput);
tempForm.attachEvent("onsubmit",function(){funWinOpen("",width,height,name);});
document.body.appendChild(tempForm);
tempForm.fireEvent("onsubmit");
tempForm.submit();
document.body.removeChild(tempForm);
}
function openNewWin_IE11(strUrl,strParam,width,height,name)
{
var tempForm = document.createElement("form");
tempForm.id="tempForm1";
tempForm.method="post";
tempForm.action=strUrl;
tempForm.target=name;
var hideInput = document.createElement("input");
hideInput.type="hidden";
hideInput.name= "param"
hideInput.value= strParam;
tempForm.appendChild(hideInput);
tempForm.addEventListener("onsubmit",function(){funWinOpen("",width,height,name);});
document.body.appendChild(tempForm);
tempForm.submit();
document.body.removeChild(tempForm);
}
function funWinOpen(strUrl,width,height,WinName)
{
var top=;
var left=;
if (height =='' && width==''){
width=screen.availWidth;
height=screen.availHeight;
}else if (height >screen.availHeight && width>screen.availWidth){
width=screen.availWidth;
height=screen.availHeight;
}else{
top=(screen.availHeight-height)/;
left=(screen.availWidth-width)/;
}
var newWindow = window.open(strUrl,WinName,'width='+width+'px,height='+height+'px,dependent,left='+left+',top='+top+',status=no,toolbar=false,menubar=no,scrollbars=yes,resizable=yes',true);
}

  预览效果图:

  C# 使用FileUpload控件上传图片,将文件转换成二进制进行存储与读取

  

上一篇:VUE项目快速构建


下一篇:Http相关