文件上传&保存在Sql数据库中 [英] File Upload & saved in Sql Database

查看:66
本文介绍了文件上传&保存在Sql数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加任何类型的文件,如Pdf,Excel,Doc等..并保存在sql数据库中...

I want to add any type of file like Pdf, Excel,Doc etc.. & saved in sql Database...

推荐答案

首先,你需要使用varbinary数据类型在表中添加列。

然后你必须转换字节数组中的文件



First , you need to add column in your table with varbinary datatype.
Then you have to convert file in byte array

string sPath ="";//your file name goes here
byte[] ydata = null;
FileInfo fInfo = new FileInfo(sPath);
long lNumBytes = fInfo.Length;
 
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
//Use BinaryReader to read file stream into byte array.
BinaryReader br = new BinaryReader(fStream);
ydata = br.ReadBytes((int)lNumBytes);
return ydata;





您可以使用此生成的字节array作为Insert语句中的参数值。



You can use this generated byte array as a parameter value in Insert statement.


您应该将文件保存到文件夹并将Url保存到dataBase。



以下是示例代码...



代码将文件上传到文件夹



You Should save file to Folder and save Url to dataBase.

Here is sample code...

Code To upload Your File to folder

YourFunctionToUploadImage()
{
  //Check FileUpload controll has File Or not
  if (FileUploadControll.HasFile)
  { 
         
         //check if file already Exists in Folder
         if (File.Exists(Server.MapPath("~/Folder_Name/" + FileUploadControll.FileName)))
         {
               lblUploadstatus.Text = "File Already Exists. Rename filename";
         }
         else
         {
               //To Save Image To your Specific Location.
               //srever.mappath takes us to Folder which containing our application
               FileUploadControll.SaveAs(Server.MapPath("~/Folder_Name/" + FileUploadControll.FileName));
               string FileUrl = Server.MapPath("~/Folder_Name/" + FileUploadControll.FileName;
               //Save This Url To your Database.
               lblUploadstatus.Text = "Upload Status : File Uploaded Successfully";
         } 
         
            
   }
   else 
   {
      lblUploadstatus.Text = "Please Select File";
   }
}





代码将从文件夹中删除所有文件





Code To Retrive All files form Folder

PageLoadEvent()
{
    //use DirectoryInfo to get all File's Information
    DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/Folder_Name/"));
    FileInfo[] fi = dir.GetFiles();
    //Here You Will Get All Files in fi[].
}





希望此帮助



Hope This Help


有一个名为varbinary的SQL数据类型可用于在数据库中存储二进制文件。

请从MSDN文档中查看此主题,以便为您的解决方案进行自定义。

http://technet.microsoft.com/en-us/library/ms188362.aspx [ ^ ]

希望这会有所帮助。
there is a SQL datatype called varbinary which you can use for storing binary files inside a database.
Please go through this topic from MSDN documentation to customize for your solution.
http://technet.microsoft.com/en-us/library/ms188362.aspx[^]
Hope this helps.


这篇关于文件上传&保存在Sql数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆