状况描述:

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

效果图:

  

  点击【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控件上传图片,将文件转换成二进制进行存储与读取的更多相关文章

  1. php将文件转换成二进制输出[转]

    header( "Content-type: image/jpeg"); $PSize = filesize('1.jpg'); $picturedata = fread(fope ...

  2. java实现文件转换成二进制存储与取出

    一.功能描述: 将文件转成二进制数据放入数据库中,需要的时候,便可以取出安装与使用. 二.数据库: 建立一个数据库字段存放转成二进制的图片,这个字段有一个要求就是要设置成blob类型的 CREATE  ...

  3. 033. asp.netWeb用户控件之二将页面转换成web控件和使用Web控件显示热点新闻

    访问Web用户控件的属性 ASP.NET提供的各种服务器控件都有其自身的属性和方法,程序开发人员可以灵活地使用服务器控件中的属性和方法开发程序.在用户控件中,程序开发人员也可以自行定义各种属性和方法, ...

  4. asp.net使用FileUpload控件上传图片且重命名

    我在根目录下创建了一个Images图片存放文件夹,上传的图片都在这 下面贴代码 if (FileUpload1.HasFile) { string filename = FileUpload1.Fil ...

  5. asp.net FileUpload 控件上传文件 以二进制的形式存入数据库并将图片显示出来

    图片上传事件代码如下所示: byte[] binary = upload.FileBytes; StringBuilder sqlStrSb = new StringBuilder(); sqlStr ...

  6. Winform控件输入的字母转换成大写

    private void textBoxHbh_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar >= 'a' & ...

  7. net9:图片文件转换成二进制流存入SQL数据库,以及从数据库中读取二进制流输出文件

    原文发布时间为:2008-08-10 -- 来源于本人的百度文章 [由搬家工具导入] using System;using System.Data;using System.Configuration ...

  8. webform FileUpload控件实例应用 上传图片

    首先在根目录下建一个"images"文件: HTML: <form id="form1" runat="server"> < ...

  9. .NET中的FileUpload控件的使用-原生JS(二)

    本篇使用原生JS进行数据传输,使用FileUpload控件上传文件,适配IE. HTML <div class="container"> <div class=& ...

随机推荐

  1. java.lang.reflect.MalformedParameterizedTypeException异常问题

    做dubbo框架集成的时候,出现的问题,本来的原来的工程没有错误,引入dubbo后报错,原因是spring的jar文件冲突,我用的spring是4.x,dubbo引入的是2.5所以需要去掉,相关的po ...

  2. 优先队列的二叉堆Java实现

    package practice; import edu.princeton.cs.algs4.StdRandom; public class TestMain { public static voi ...

  3. Topshelf便捷创建Windows服务

    结合Quartz.net学习,前提已经创建了一个定时任务,可见 <定时调度框架:Quartz.net> (基于配置文件形式) 首先引用Topshelf.dll 自定义服务TestServi ...

  4. 【全面总结】js获取元素位置大小

    [js获取元素位置+元素大小]全面总结 目录 1.关于offset offsetParent(只读) offsetTop(只读) offsetLeft(只读) offsetHeight(只读) off ...

  5. Charles 抓包

    声明:本文为依依Love博主原创文章,未经博主允许不得转载   1. 简介: 2. 安装包下载: 3. 安装并替换破解版的jar包 4.设置mac代理 5.  安装证书: 6.  设置手机抓包     ...

  6. JSON与String之间互转

    一,String转json 这个JSON.parse()与eval()都可以实现,但是它们是有区别的, JSON.parse对json字符串要求比eval()更为严格,key名称(例如name)全部必 ...

  7. 结对编程四则运算gui

    码市地址:https://git.coding.net/linzhao/sizeyunsuangui.git 林 钊 -- 201421123105 吴世荣 -- 201421123119 王坤彬 - ...

  8. Alpha阶段-个人总结

    一.五个问题 1.第三章中提到了"质量"和"按时交付"的问题,我想问,世事难料,当两者不能兼得的时候,我是保证质量却无法按时交付,还是水两下保证按时交付呢? 2 ...

  9. 4th-结对编程2

    0x00 Coding Coding地址/小伙伴的博客地址 合作伙伴:庞伊凡(201421123011).赵娅汀(201421123012) 0x01 题目描述 上一周大家为四则运算程序设计了2-3个 ...

  10. 【Alpha】第一次项目冲刺

    今日站立式会议照片 每个人的工作 小组成员 昨天完成的工作 今天计划完成的工作 李志霖 继续访问用户以深入了解他们的需求,分别采用面访,qq等不同方式对意见进行了采集,面访了30个人,qq空间以链接的 ...