【问题标题】:Storing upload file as binary data in SQL Server database将上传文件作为二进制数据存储在 SQL Server 数据库中
【发布时间】:2015-11-27 20:01:17
【问题描述】:

我一直在努力解决这个问题。我正在尝试将文件上传到服务器并将其保存为数据库中的二进制数据。

我知道如何将文件上传到服务器,并且工作正常。

我需要知道如何将文件保存为数据库中的二进制数据。

这是我已经完成的:

在 SQL Server 数据库中,我有一个名为 files 的表,其中包含以下列:

Id, int, identity column 
FileName, nvarchar(50) 
UploadDate, datetime
FileContent, varbinary(max)

HomeController.cs:

[HttpPost]
public ActionResult Index(HttpPostedFileBase[] files)
{
    try
    {
        foreach (var file in files)
        {
            // extract only the filename
            var fileName = Path.GetFileName(file.FileName);

            // extract the file content to byte array
            var content = new byte[file.ContentLength];
            // reads the content from stream
            file.InputStream.Read(content, 0, file.ContentLength);

            //get file extesion
            var fileExtension = Path.GetExtension(fileName);
            //save file name as uniqe
            var uniqueFileName = Guid.NewGuid().ToString();

            Files fu = new Files
            {
                FileName = uniqueFileName,
                UploadDate = DateTime.Now,
                FileContent = content
            };

            DB.Files.Add(fu);
            DB.SaveChanges();
        }
    }
    catch (Exception e) { }

    // redirect back to the index action to show the form once again
    return RedirectToAction("Index");
}

index.cshtml:

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="files" multiple/>
    <input type="submit" value="OK" />
}

这段代码在数据库表中插入一条记录,记录如下:

Id  FileName                                UploadDate              FileContent
1   716d30a5-8019-4ec9-a5e9-5b3966296bfc    2015-11-27 21:50:27.037 <Binary data>

我不知道为什么fileContent 列会填满文本&lt;Binary data&gt;

【问题讨论】:

  • InputStream.Read 不像你认为的那样工作,你必须使用重新调整的 int 并继续阅读,直到你完全阅读数据。
  • 这就是 SQL Server 显示二进制数据的方式。您的数据没有被神奇地转换为“二进制数据”。
  • @ataravati,不是每个人都有 15 年的经验:) 现在我知道了......谢谢

标签: sql-server asp.net-mvc entity-framework


【解决方案1】:

由于文件内容数据类型为二进制,Sql server 内部将其作为二进制数据类型进行管理。您无法通过查看 Table 直接看到二进制文件。

如果你想在SSMS中查看二进制数据,试试this

这是一个检索binday数据的例子

// Assumes that connection is a valid SqlConnection object.
SqlCommand command = new SqlCommand(
  "SELECT pub_id, logo FROM pub_info", connection);

// Writes the BLOB to a file (*.bmp).
FileStream stream;                          
// Streams the BLOB to the FileStream object.
BinaryWriter writer;                        

// Size of the BLOB buffer.
int bufferSize = 100;                   
// The BLOB byte[] buffer to be filled by GetBytes.
byte[] outByte = new byte[bufferSize];  
// The bytes returned from GetBytes.
long retval;                            
// The starting position in the BLOB output.
long startIndex = 0;                    

// The publisher id to use in the file name.
string pubID = "";                     

// Open the connection and read data into the DataReader.
connection.Open();
SqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess);

while (reader.Read())
{
  // Get the publisher id, which must occur before getting the logo.
  pubID = reader.GetString(0);  

  // Create a file to hold the output.
  stream = new FileStream(
    "logo" + pubID + ".bmp", FileMode.OpenOrCreate, FileAccess.Write);
  writer = new BinaryWriter(stream);

  // Reset the starting byte for the new BLOB.
  startIndex = 0;

  // Read bytes into outByte[] and retain the number of bytes returned.
  retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize);

  // Continue while there are bytes beyond the size of the buffer.
  while (retval == bufferSize)
  {
    writer.Write(outByte);
    writer.Flush();

    // Reposition start index to end of last buffer and fill buffer.
    startIndex += bufferSize;
    retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize);
  }

  // Write the remaining buffer.
  writer.Write(outByte, 0, (int)retval - 1);
  writer.Flush();

  // Close the output file.
  writer.Close();
  stream.Close();
}

// Close the reader and the connection.
reader.Close();
connection.Close();

来源:MSDN

【讨论】:

  • 那么,你说插入到数据库的数据没问题?
  • 是的,它被插入了,现在你必须检索它。msdn.microsoft.com/en-us/library/87z0hy49(v=vs.110).aspx
  • 我试过这个:“SELECT sys.fn_sqlvarbasetostr(FileContent) From [dbo].[Files]”结果是这样的——“操作数类型冲突:varbinary(max) 与 sql_variant 不兼容”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多