上传的后台处理文件uploadFile.aspx.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;
using System.Text;
using System.IO;
public partial class uploadFile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//实现文件上传
protected void btUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileContentType = FileUpload1.PostedFile.ContentType;
if (fileContentType == "image/bmp" || fileContentType == "image/gif" || fileContentType == "image/pjpeg")
{
// 客户端文件路径
string name = FileUpload1.PostedFile.FileName;
FileInfo file = new FileInfo(name);
// 文件名称
string fileName = file.Name;
// 服务器端文件路径
string webFilePath = Server.MapPath("Upload/" + fileName);
if (!File.Exists(webFilePath))
{
try
{
// 使用 SaveAs 方法保存文件
FileUpload1.SaveAs(webFilePath);
this.lMsg.Text = "提示:文件“" + fileName + "”上传成功!";
this.lPathInfo.Text = "Upload/" + fileName;
this.iPic.ImageUrl = "Upload/" + fileName;
}
catch (Exception ex)
{
this.lMsg.Text = "提示:文件上传失败,失败原因:" + ex.Message;
}
}
else
{
this.lMsg.Text = "提示:文件已经存在,请重命名后上传";
}
}
else
{
this.lMsg.Text = "提示:文件类型不符";
}
}
}
}