文件保存到数据库

上传:

private void UploadFile()
  {   
   System.Web.HttpPostedFile file = this.uploadFile.PostedFile;
   string fileName = file.FileName;
   if(fileName.Trim() == "")
   {
    WebCommon.ShowMessage(this.Page,"Please input the file name.");
    return;
   }
   fileName = fileName.Substring(fileName.LastIndexOf("\\")+1);
   int fileLength = file.ContentLength;
   byte[] fileBytes = new byte[fileLength];
   file.InputStream.Read(fileBytes,0,fileLength);
   BBA.BLL.TelUserListBiz biz = new TelUserListBiz();
   BBA.Model.TelUserListData data = new TelUserListData();
   data.FileName = fileName;
   data.FormID = this.lblFormID.Text;
   data.UserList = fileBytes;
   data.Discripton = "User List";

   if(biz.Exists(data.FormID))
   {    
    biz.Update(data);
   }
   else
   {   
    biz.Insert(data);
   }
   this.lblFileName.Text = "<br>File Name: " + fileName + "<br>";
  }

public bool Insert (TelUserListData data)
{
   #region Populate Parameters
   SqlParameter[] arParams = new SqlParameter[4];

   arParams[0] = new SqlParameter("@FormID", SqlDbType.VarChar, 50);
   arParams[0].Value = data.FormID;
   arParams[1] = new SqlParameter("@UserList", SqlDbType.Image);
   arParams[1].Value = data.UserList;
   arParams[2] = new SqlParameter("@FileName", SqlDbType.VarChar, 256);
   arParams[2].Value = data.FileName;
   arParams[3] = new SqlParameter("@Discripton", SqlDbType.VarChar, 50);
   arParams[3].Value = data.Discripton;
   #endregion

   SqlHelper.ExecuteNonQuery(this.ConnectionString, CommandType.StoredProcedure, "usp_TelUserList_Insert", arParams);
   return true;
  }
 

 

下载:

  private void btnView_Click(object sender, System.EventArgs e)
  {
   BBA.BLL.TelUserListBiz biz = new TelUserListBiz();
   string formID = this.lblFormID.Text;
   if(biz.Exists(formID))
   {
    DataTable dt = biz.SelectByFormID(formID);
    string fileName = dt.Rows[0]["FileName"].ToString();
    byte[] fileBytes = (byte[])dt.Rows[0]["UserList"];
    int fileLength = fileBytes.Length;
    Response.Clear();
    Response.ClearHeaders();
    Response.Buffer = false;
    Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
    Response.AppendHeader("Content-Length", fileLength.ToString());
    Response.ContentType = "application/octet-stream";
    Response.BinaryWrite(fileBytes);
    Response.Flush();
    Response.End();
   }
   else
   {
    this.btnView.Enabled = false;
    WebCommon.ShowMessage(this.Page,"File not exists.");
   }
  }

SQL:

CreatePROCEDURE [dbo].[usp_TelUserList_Insert]
    @FormID varchar(50),
    @UserList image,
    @FileName varchar(256),
    @Discripton varchar(50)
AS
INSERT [dbo].[TelUserList]
(
    [FormID],
    [UserList],
    [FileName],
    [Discripton]
)
VALUES
(
    @FormID,
    @UserList,
    @FileName,
    @Discripton
)

你可能感兴趣的:(数据库)