在做一个信息管理平台时用到了图片,就像做一个上传的
正好用的是asp.net ajax
就试着做了一个
不很好
自定义用户控件文件 PicUpload.ascx
<%@ control language="C#" autoeventwireup="true" inherits="Admin_PicUpload, App_Web_mboefw14" %>
<asp:Image ID="EP_Image" runat="server" Height="160px" ImageUrl='<%# Bind("EP_Pic") %>'
Width="314px" />
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上传" />
自定义用户控件文件 PicUpload.ascx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Admin_PicUpload : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
bool fileOK = false;
//获取根文件绝对路径
string path = Server.MapPath("~/UpLoad/");
//如上传了文件,就判断文件格式
FileUpload FU = FileUpload1;
if (FU.HasFile)
{
string fileExtension = System.IO.Path.GetExtension(FU.FileName).ToLower();
string[] allowedExtensions ={ ".gif", ".jpg", ".png", ".bmp", };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
}
}
}
//调用saveas方法,实现上传文件
if (fileOK)
{
try
{
FileUpload1.SaveAs(path + System.DateTime.Now.ToString("yyyyMMddhhmmss")+FU.FileName);
EP_Image.ImageUrl = "../Upload/" + System.DateTime.Now.ToString("yyyyMMddhhmmss") + FU.FileName;
Button1.Text = "上传成功";
}
finally
{
}
}
else
{
Button1.Text = "上传失败,格式不允许";
}
}
}
方案二、摘自http://www.netfocus.cn/article950.html
1:主页面中使用UpdatePanel,然后UpdatePanel里面放置的不是FileUpload控件,而是一个Iframe
2:这个iframe在链接一个新的页面,那个页面里面有FileUpload控件。
3:上传完毕后,告诉主页面上传得结果
先看一个直接使用FileUpload的例子:这个例子里面,服务端是无法找到上传文件的。
<atlas:UpdatePanel ID="up1" Mode="Conditional" runat="server">
<ContentTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
< SPAN>ContentTemplate>
< SPAN>atlas:UpdatePanel>
看看,我们该如何实现
1:新建主页面Default.aspx
在适当的位置,放置一个上传附件的UpdatePanel区域
<atlas:UpdatePanel ID="up_attachment" Mode="Conditional" runat="server">
<ContentTemplate>
<iframe id="file" name="file" src="attachment.aspx">< SPAN>iframe>
< SPAN>ContentTemplate>
< SPAN>atlas:UpdatePanel>
2:新建上传文件的页面attachment.aspx,然后放上FileUpload控件
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="OK" OnClick="Button1_Click" />
< SPAN>div>
3:在attachment.aspx里面,上传文件之后调用主页面的js,报告上传情况。这是函数原型:
<script>
window.top.callBack(fileName);
< SPAN>script>
4:Default.aspx主页面里面增加这个函数,处理返回值
<script>
function callBack(fileName)
{
document.getElementById('Attach1').innerHTML=fileName;
}
< SPAN>script>