FileUpload选择图片后先预览图片,然后上传。
使用到FileUpload的onchange事件,及使用一般处理程序(.ashx)来预览图片。
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function uploadFile(filePath) {
if (filePath.length > 0) {
__doPostBack('btnUploadFile', '');
formReset();
}
}
function formReset() {
document.getElementById("form1").reset()
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Image ID="Image1" runat="server" ImageAlign="Middle" /></div>
<div style="width:800px;margin:0 auto;visibility:hidden">
<asp:FileUpload ID="FileUpload" runat="server" accept="image/*" οnchange="uploadFile(this.value)"/>
</div>
<div style="width:800px;margin:0 auto;">图片格式为.jpg, .gif, .bmp, .png</div>
<div style="width:800px;margin-top:10px; height: 16px; margin-left: auto; margin-right: auto; margin-bottom: 0;"><asp:Label ID="lbl_pic"
runat="server" ForeColor="#FFFF66" Font-Bold="True" Font-Italic="False"
Font-Overline="False"></asp:Label>
</div>
<div style="width:800px;margin:0 auto;">
<button type="button" οnclick="document.getElementById('FileUpload').click();">选择图片</button>
</div>
<div style="visibility:hidden">
<asp:LinkButton ID="btnUploadFile" runat="server" οnclick="btnUploadFile_Click">上传图片</asp:LinkButton>
</div>
</form>
</body>
</html>
formReset()防止上传后刷新页面重复提交。
protected void btnUploadFile_Click(object sender, EventArgs e)
{
if (!this.FileUpload.HasFile)
{
lbl_pic.Text = "请选择要使用的照片!";
return;
}
string fileExtension = Path.GetExtension(this.FileUpload.FileName).ToLower();
if (!isImage(fileExtension))
{
lbl_pic.Text = "图片格式不对,请重新选择!";
return;
}
Session["UploadBytes"] = this.FileUpload.FileBytes;
this.Image1.ImageUrl = "~/ImagePreview.ashx"
string imageName = Guid.NewGuid().ToString().Trim() + ".jpg";
string virpath = "/temp/";
if (!Directory.Exists(Server.MapPath(virpath)))
{
Directory.CreateDirectory(Server.MapPath(virpath));
}
string mappath = Server.MapPath(virpath + imageName);
if ((Session["UploadBytes"]) != null)
{
byte[] buffer = (byte[])(Session["UploadBytes"]);
File.WriteAllBytes(mappath, buffer);
}
}
/// <summary>
/// 验证是否指定的图片格式
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public bool isImage(string str)
{
bool isimage = false;
string thestr = str.ToLower();
string[] allowExtension = { ".jpg", ".gif", ".bmp", ".png" };
for (int i = 0; i < allowExtension.Length; i++)
{
if (thestr == allowExtension[i])
{
isimage = true;
break;
}
}
return isimage;
}
一般处理程序(ImagePreview.ashx):
/// <summary>
/// Handler1 的摘要说明
/// </summary>
public class ImagePreview : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
if ((context.Session["UploadBytes"]) != null)
{
byte[] buffer = (byte[])(context.Session["UploadBytes"]);
context.Response.BinaryWrite(buffer);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
Web.config中增加配置:
<system.web>
<httpHandlers>
<add verb="*" path="ImagePreview.ashx" type="命名空间.ImagePreview"/>
</httpHandlers>
</system.web>