用fileupload上传文件
<asp:FileUpload ID="CVFileUpload" runat="server" />
<asp:Button ID="CVUpload" runat="server" Font-Overline="False" Font-Size="8pt" OnClick="CVUpload_Click"
Text="Upload" CausesValidation="False" />
<asp:HyperLink ID="CV" runat="server" NavigateUrl='<%# Bind("CV") %>' Target="_blank"
Visible="False">File Uploaded</asp:HyperLink>
<asp:Button ID="CVChangeButton" runat="server" Font-Size="8pt" OnClick="CVChangeButton_Click"
Text="Change" Visible="False" CausesValidation="False" />
protected void CVUpload_Click(object sender, EventArgs e)
{
FileUpload myFile = (FileUpload)FormView1.FindControl("CVFileUpload");
HyperLink hypl = (HyperLink)FormView1.FindControl("CV");
if (myFile.PostedFile != null)
{
string nam = myFile.PostedFile.FileName;
//取得文件名(抱括路径)里最后一个"."的索引
int i = nam.LastIndexOf(".");
//取得文件扩展名
string newext = nam.Substring(i);
//这里我自动根据日期和文件大小不同为文件命名,确保文件名不重复
DateTime now = DateTime.Now;
string newname = now.Year.ToString() + "_" + now.Month.ToString() + "_" + now.Day.ToString() + "_" + myFile.PostedFile.ContentLength.ToString();
//保存文件到你所要的目录,这里是IIS根目录下的upload目录.你可以改变.
//注意: 我这里用Server.MapPath()取当前文件的绝对目录.在asp.net里"\"必须用"\\"代替
//myFile.PostedFile.SaveAs(Server.MapPath("http://www.cnblogs.com/liuweicfyj/admin/file://upload//" + newname + newext));
String path = "Upload\\" + newname + newext;
myFile.PostedFile.SaveAs(Server.MapPath(path));
//得到这个文件的相关属性:文件名,文件类型,文件大小
//fname.Text = myFile.PostedFile.FileName;
//fenc.Text = myFile.PostedFile.ContentType;
//fsize.Text = myFile.PostedFile.ContentLength.ToString();
hypl.NavigateUrl = path;
hypl.Visible = true;
myFile.Visible = false;
((Button)FormView1.FindControl("CVUpload")).Visible = false;
((Button)FormView1.FindControl("CVChangeButton")).Visible = true;
}
}
protected void CVChangeButton_Click(object sender, EventArgs e)
{
((FileUpload)FormView1.FindControl("CVFileUpload")).Visible = true;
((Button)FormView1.FindControl("CVUpload")).Visible = true;
((Button)FormView1.FindControl("CVChangeButton")).Visible = false;
((HyperLink)FormView1.FindControl("CV")).Visible = false;
File.Delete(Server.MapPath(((HyperLink)FormView1.FindControl("CV")).NavigateUrl));
((HyperLink)FormView1.FindControl("CV")).NavigateUrl = "";
}