//定义一个文件打开控件
OpenFileDialog ofd = new OpenFileDialog();
//设置打开对话框的初始目录,默认目录为exe运行文件所在的路径
ofd.InitialDirectory = Application.StartupPath;
//设置打开对话框的标题
ofd.Title = "请选择要打开的文件";
//设置打开对话框可以多选
ofd.Multiselect = true;
//设置对话框打开的文件类型
ofd.Filter = "所有文件|*.*";
//设置文件对话框当前选定的筛选器的索引
ofd.FilterIndex = 2;
//设置对话框是否记忆之前打开的目录
ofd.RestoreDirectory = true;
if (ofd.ShowDialog() == DialogResult.OK)//打开文件选择框
{
//获取用户选择的文件完整路径
string filePath = ofd.FileName;
//重新获取文件信息
var fileInfo = new FileInfo(filePath);
//获取文件大小
float filesize = (float)fileInfo.Length / (1024 * 1024);
if (filesize > 10)
{
MessageBox.Show("文件不能超过10MB");
return;
}
//获取对话框中所选文件的文件名和扩展名,文件名不包括路径
string fileName = fileInfo.Name;
//10mb
//获取文件类型
string fileType = fileInfo.Extension.ToLower();
if (fileType == ".txt" || fileType == ".doc" || fileType == ".docx" || fileType == ".pdf")
{
byte[] textres= getbyte(filePath);
InsertData(fileName, filesize.ToString("0.00"), textres, 1);
}
else
{
MessageBox.Show("文件类型错误,允许类型.txt .doc .docx .pdf");
return;
}
}
//根据文件获取byte[]
//根据文件获取byte[]
private static byte[] getbyte(string path) {
byte[] byteData ;
using (FileStream fs=new FileStream(path,FileMode.Open,FileAccess.Read))
{
using (BinaryReader bg=new BinaryReader(fs)) {
byteData = bg.ReadBytes((int)fs.Length);
}
}
return byteData;
}
//byte[]存入数据库
//byte[]存入数据库
private static string InsertData(string FileName,string filesize, byte[] UpLoad_Content, int Amount)
{
string strConn = "Data Source=.;Initial Catalog=ceshi;User ID=sa;Password=sa.";
string sql = "INSERT INTO[dbo].[FS_UpLoadFile](Name,ContentSize, UpLoad_Content,Amount) VALUES(@FileName , @filesize , @UpLoad_Content , @Amount)";
DataTable dt = new DataTable();
SqlConnection Conn = new SqlConnection(strConn);
Conn.Open();
SqlCommand cmd = new SqlCommand(sql, Conn);
cmd.Parameters.Add("@FileName", SqlDbType.NVarChar, 50);
cmd.Parameters.Add("@filesize", SqlDbType.NVarChar, 50);
cmd.Parameters.Add("@UpLoad_Content", SqlDbType.Binary);
cmd.Parameters.Add("@Amount", SqlDbType.Int);
cmd.Parameters["@FileName"].Value= FileName;
cmd.Parameters["@filesize"].Value = filesize;
cmd.Parameters["@UpLoad_Content"].Value = UpLoad_Content;
cmd.Parameters["@Amount"].Value = Amount;
int result = cmd.ExecuteNonQuery();
Conn.Close();
if (result > 0)
{
return "上传成功";
}
else
{
return "上传失败";
}
数据结构;