文件上传实例
![](https://images201506.cnblogs.com/blog201506/725488/201506/021308285232034.png)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using data;
using dataDA;
using System.IO;
namespace web1
{
public partial class WebForm5 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//上传到数据库image字段
protected void Button1_Click(object sender, EventArgs e)
{
UploadData data = new UploadData();
data.Owners = "路人甲";
data.Name = data.Owners.ToString()+DateTime.Now.ToString("yyyyMMddhhmmssms")+ FileUpload1.FileName;
data.Fil = FileUpload1.FileBytes ;
new UploadDA().Insert(data);
}
//索引查看数据库图片
protected void Button2_Click(object sender, EventArgs e)
{
UploadData data = new UploadDA().Select(Convert.ToInt16(TextBox1.Text));
if (data != null)
{
FileStream fr = new FileStream(Server.MapPath("temp.jpg"), FileMode.Create);
fr.Write(data.Fil, 0, data.Fil.Length);
fr.Close();
Image1.ImageUrl = "temp.jpg";
}
}
//批量上传到硬盘
protected void Button3_Click(object sender, EventArgs e)
{
try
{
int i = 0;
foreach (Control ctl in form1.Controls)
{
if (ctl is FileUpload)
{
FileUpload up = ctl as FileUpload;
i++;
if (up.HasFile)
{
string path = Server.MapPath("img/"+DateTime.Now.ToString("yyyyMMddhhmmssms")+i.ToString("00")+up.FileName);
up.SaveAs(path);
}
}
}
}
catch
{
}
}
//显示图片
protected void Button4_Click(object sender, EventArgs e)
{
Image1.ImageUrl = "img.aspx?id="+TextBox1.Text.Trim();
}
//单个保存到硬盘
protected void Button6_Click(object sender, EventArgs e)
{
string path = Server.MapPath("img/" + DateTime.Now.ToString("yyyyMMddhhmmssms") + FileUpload1.FileName);
FileUpload1.SaveAs(path);
}
//批量保存到数据库
protected void Button5_Click(object sender, EventArgs e)
{
foreach (Control ctl in form1.Controls)
{
if (ctl is FileUpload)
{
FileUpload up = ctl as FileUpload;
UploadData data = new UploadData();
data.Owners = "路人甲";
data.Name = data.Owners.ToString() + DateTime.Now.ToString("yyyyMMddhhmmssms") + up.FileName;
data.Fil = up.FileBytes;
new UploadDA().Insert(data);
}
}
}
}
}