本文简单地使用Asp.net中FileUpload组件实现简单的文件的上传
页面前台部分
<asp:FileUpload ID="myFile" runat="server" BorderColor="Silver" BorderStyle="Solid" BorderWidth="1px" />
附件实体类
/// <summary>
/// 附件,加一个实体化类是为了用orm的方式保存附件对象,属性根据自己需要添加
/// </summary>
public class Attachment
{
public int Id { get; set; }
public string Name { get; set; }
public string ExtendName { get; set; }
public long Size { get; set; }
public int IsUsed { get; set; }
public string Descript { get; set; }
public byte[] Content { get; set; }
}
/// 附件,加一个实体化类是为了用orm的方式保存附件对象,属性根据自己需要添加
/// </summary>
public class Attachment
{
public int Id { get; set; }
public string Name { get; set; }
public string ExtendName { get; set; }
public long Size { get; set; }
public int IsUsed { get; set; }
public string Descript { get; set; }
public byte[] Content { get; set; }
}
页面后台代码,页面上传按钮的单击事件中添加代码,调用如下函数
void saveToDataBase()
{
string fileName = myFile.FileName;
string fileType = myFile.PostedFile.ContentType;
long size = myFile.FileContent.Length;
string descript = myDescript.Text;
//new一个实体对象
Attachment attachmentObj = new Attachment();
attachmentObj.Id = 0;
attachmentObj.Name = fileName;
attachmentObj.ExtendName = fileType;
attachmentObj.Size = size;
attachmentObj.Descript = descript;
attachmentObj.Content = myFile.FileBytes;
//orm方式保存附件对象,如NHibernate等
save(attachmentObj);
//其他处理代码,或注册客户端脚本事件或语句
}
{
string fileName = myFile.FileName;
string fileType = myFile.PostedFile.ContentType;
long size = myFile.FileContent.Length;
string descript = myDescript.Text;
//new一个实体对象
Attachment attachmentObj = new Attachment();
attachmentObj.Id = 0;
attachmentObj.Name = fileName;
attachmentObj.ExtendName = fileType;
attachmentObj.Size = size;
attachmentObj.Descript = descript;
attachmentObj.Content = myFile.FileBytes;
//orm方式保存附件对象,如NHibernate等
save(attachmentObj);
//其他处理代码,或注册客户端脚本事件或语句
}
后面的话:
当然如果想做得比较完美的话,
1)首先在客户端可以添加一些验证,什么文件允许添加,服务器端也要有一些验证。
2)多个文件同时上传等
3)Ajax进度条等
......