簡體   English   中英

在 varbinary(MAX) 中上傳文件

[英]Uploading files in varbinary(MAX)

我有一個數據庫表,其中包含兩個 varbinary(max) 類型的字段,用於存儲文件。

但是,我無法按預期上傳文件。 我已經被這個問題難住了很長時間,我不確定我能做些什么來解決它。 有一條錯誤信息:

An exception of type 'System.Data.SqlClient.SqlException' occurred in
System.Data.dll but was not handled in user code
Additional information: Incorrect syntax near the keyword 'title'.

必須在 ASP.NET 中實現 3 層架構。

數據訪問層

public class Submission { 

  private string _title;
  private byte[] _slides, _codes;

  //Connection string 
  private string _connStr = Properties.Settings.Default.DBConnStr;

  public Submission(string title, byte[] slides, byte[] codes) {
  _title = title;
  _slides = slides;
  _codes = codes;
  }

  //UPLOAD files
  public int SubmissionInsert()
  {
          string queryStr = "INSERT INTO Submission(title,slides,codes)" +
              "VALUES('" +
              _title + "', '" +
              _slides + "', '" +
              _codes + "')";

          SqlConnection con = new SqlConnection(_connStr);
          SqlCommand cmd = new SqlCommand(queryStr, con);

          con.Open();
          int nofRow = 0;
          nofRow = cmd.ExecuteNonQuery();

          con.Close();

          return nofRow;
  }
}

業務邏輯層

public class SubmissionBLL
{
    public string submissionUpload(string title, byte[] slides, byte[] codes)
    {
        string returnValue = "";

        if (title.Length == 0)
            returnValue+= "Title cannot be empty";
        if (slides == null)
            returnValue += "Slides cannot be empty";
        if (codes == null)
            returnValue += "Codes cannot be empty";

        //if there are no errors
        if (returnValue.Length == 0)
        {
            Submission sub = new Submission(title,slides,codes);

            int nofRows = 0;
            nofRows = sub.SubmissionInsert();

            if (nofRows > 0)
                returnValue = "Submission is successful!";
            else
                returnValue = "Submission failure. Please try again.";
        }

        return returnValue;
  }

表示層 - 代碼隱藏

 protected void btn_submit_Click(object sender, EventArgs e)
    {
        string input = "";
        byte[] slideArr = null, codeArr= null;

        string strTestFilePath, strTestFileName, strContentType;
        Int32 intFileSize, intFileLength;
        Stream strmStream;

        if (f_codes.HasFile)
        {
                strTestFilePath = f_codes.PostedFile.FileName;
                strTestFileName = Path.GetFileName(strTestFilePath);
                intFileSize = f_codes.PostedFile.ContentLength;
                strContentType = f_codes.PostedFile.ContentType;

                //Convert the source codes file to byte stream to save to database
                strmStream = f_codes.PostedFile.InputStream;
                intFileLength = (Int32)strmStream.Length;
                codeArr = new byte[intFileLength + 1];
                strmStream.Read(codeArr, 0, intFileLength);
                strmStream.Close();

        }

         if (f_slide.HasFile)
        {
                strTestFilePath = f_slide.PostedFile.FileName;
                strTestFileName = Path.GetFileName(strTestFilePath);
                intFileSize = f_slide.PostedFile.ContentLength;
                strContentType = f_slide.PostedFile.ContentType;

                strmStream = f_slide.PostedFile.InputStream;
                intFileLength = (Int32)strmStream.Length;
                slideArr = new byte[intFileLength + 1];
                strmStream.Read(slideArr, 0, intFileLength);
                strmStream.Close();
            }

         //Pass to BLL
         input = sub.submissionUpload(tb_title.Text,slideArr,codeArr);
         //Display error messages
         lbl_message.Text = input;
    }

我嘗試使用 IntelliTrace 進行調試並顯示一條消息

ADO.NET:Execute NonQuery "INSERT INTO Submission(title,slides,codes)VALUES('My Water Saving Project', 'System.Byte[]','System.Byte[]')"


我這樣做正確嗎? 我嘗試運行,但仍然存在異常錯誤。

string queryStr = "INSERT INTO Submission(title,slides,codes)" + "VALUES('"+
            _title + "', '" +
           "0x" + BitConverter.ToString(_slides).Replace("-", "")+ "', '" +
           "0x" + BitConverter.ToString(_codes).Replace("-", "")  + "')";

"0x" + BitConverter.ToString(_slides).Replace("-", "")+ "', '" +

您不應該將字節轉換為字符串。 相反,您希望使用參數化查詢(以避免 sql 注入)並將這些字節數組直接插入數據庫。

public int SubmissionInsert(string title, byte[] slides, byte[] codes)
{
    int nofRow;
    string query = "INSERT  INTO Submission ( title, slides, codes )" +
                    "VALUES  ( @Title, @Slides, @Codes );";

    using (var con = new SqlConnection(_connStr))
    {
        con.Open();
        using (var cmd = new SqlCommand(query, con))
        {
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@Title", title);
            cmd.Parameters.AddWithValue("@Slides", slides);
            cmd.Parameters.AddWithValue("@Codes", codes);
            nofRow = cmd.ExecuteNonQuery();
        }
    }
    return nofRow;
}

您的問題與類型轉換有關。 如果您將值作為字符串插入(並且您使用這些單引號),則需要插入十六進制值,並以 0x 為前綴。

這應該可以幫助你: "0x" + BitConverter.ToString(byteArray).Replace("-", "")

I also got the same error when I am uploading doc USING ADO.NET and Storedproc.

I am using stored proc to upload word file to the table's column type varbinary(max).
There are so many examples with insert query to insert document but my scenario was stored proc. I spent lot of time in figuring out the solution. 

Stored Proc:`Alter PROC [dbo].[usp_GMS_SaveEngagementDocument](
        @pDocumentID INT=0,
        @pEngagementID INT,
        @pDocumentName NVARCHAR(100),
        @pContentType NVARCHAR(100),
        @pDocumentType NVARCHAR(100),
        @pDocumentContent VARBINARY(max)=null,
       @pUserID INT)
AS
BEGIN
--INSERT
END`



SOLUTION:

    param = new SqlParameter();
                param.ParameterName = "@pDocumentContent";
                param.Direction = ParameterDirection.Input;
                param.Value = document.DocumentContent;
                param.DbType = DbType.Binary;
                param.SqlDbType = SqlDbType.Binary;
                paramList.Add(param);



Setting SQLDBType as Binary and DbType as Binary solved my problem In calling stored proc.

END

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM