1

I am trying to upload a file and save it's binary content to my database field. Each time I try to save, it simply enters the database as 0x.

Here is the relevant code:

<form id="frmDefault" enctype="multipart/form-data" runat="server">
    <asp:FileUpload ID="fileInput" runat="server" style="margin: 8px 0 13px 0;" /><br />
    <asp:textbox rows="5" TextMode="multiline" runat="server" id="description" /><br />
    <asp:Button ID="btnUpload" Text="Upload File" runat="server" 
        onclick="btnUpload_Click" />
</form>

I establish the variable:

HttpPostedFile file = fileInput.PostedFile;

And, it hits this function:

LoadFile(gAttachmentContentID, file.InputStream, trn);

Which is defined as:

public static void LoadFile(Guid gAttachmentContentID, Stream stm, IDbTransaction trn)
{
            const int BUFFER_LENGTH = 40 * 1024;
            byte[] binFILE_POINTER = new byte[32];
            //Testing check out check in
            // 01/20/2006 Paul.  Must include in transaction
            SqlProcs.spATTACHMENTS_CONTENT_InitPointer(gAttachmentContentID, ref binFILE_POINTER, trn);

            using (BinaryReader reader = new BinaryReader(stm))
            {
                int nFILE_OFFSET = 0;
                byte[] binBYTES = reader.ReadBytes(BUFFER_LENGTH);

                while (binBYTES.Length > 0)
                {
                    // 08/14/2005 Paul.  gID is used by Oracle, binFILE_POINTER is used by SQL Server. 
                    // 01/20/2006 Paul.  Must include in transaction
                    SqlProcs.spATTACHMENTS_CONTENT_WriteOffset(gAttachmentContentID, binFILE_POINTER, nFILE_OFFSET, binBYTES, trn);
                    nFILE_OFFSET += binBYTES.Length;
                    binBYTES = reader.ReadBytes(BUFFER_LENGTH);
                }
            }
}

How can I read the correct contents in order to save the entire file to the database?

Thank you.

Edit:

    #region spATTACHMENTS_CONTENT_WriteOffset
    /// <summary>
    /// spATTACHMENTS_CONTENT_WriteOffset
    /// </summary>
    public static void spATTACHMENTS_CONTENT_WriteOffset(Guid gID, byte[] binFILE_POINTER, Int32 nFILE_OFFSET, byte[] byBYTES)
    {
        DbProviderFactory dbf = DbProviderFactories.GetFactory();
        using ( IDbConnection con = dbf.CreateConnection() )
        {
            con.Open();
            using ( IDbTransaction trn = con.BeginTransaction() )
            {
                try
                {
                    using ( IDbCommand cmd = con.CreateCommand() )
                    {
                        cmd.Transaction = trn;
                        cmd.CommandType = CommandType.StoredProcedure;
                        if ( Sql.IsOracle(cmd) )
                            cmd.CommandText = "spATTACHMENTS_CONTENT_WriteOff";
                        else
                            cmd.CommandText = "spATTACHMENTS_CONTENT_WriteOffset";
                        IDbDataParameter parID               = Sql.AddParameter(cmd, "@ID"              , gID                );
                        IDbDataParameter parFILE_POINTER     = Sql.AddParameter(cmd, "@FILE_POINTER"    , binFILE_POINTER    );
                        IDbDataParameter parMODIFIED_USER_ID = Sql.AddParameter(cmd, "@MODIFIED_USER_ID",  Security.USER_ID  );
                        IDbDataParameter parFILE_OFFSET      = Sql.AddParameter(cmd, "@FILE_OFFSET"     , nFILE_OFFSET       );
                        IDbDataParameter parBYTES            = Sql.AddParameter(cmd, "@BYTES"           , byBYTES            );
                        cmd.ExecuteNonQuery();
                    }
                    trn.Commit();
                }
                catch(Exception ex)
                {
                    trn.Rollback();
                    throw(new Exception(ex.Message, ex.InnerException));
                }
            }
        }
    }
    #endregion
15
  • 1
    When you debug, what's the value of Request.Files? Also, you can just use fileInput.PostedFile instead of looping through the Request.Files collection Commented Feb 18, 2013 at 18:55
  • 1
    SqlProcs seems to be an object or class to encapsulate your stored procedures, this seems to be custom made, so we don't know how it works. I haven't used SQL Server and .NET to store binary data, but if the query is built using simple strings, then the binary data must be escaped of any escape character the database uses. Commented Feb 18, 2013 at 20:35
  • 1
    I think what it's trying to do is fetch and write the data in chunks. It uses _InitPointer and _WriteOffset to write one buffer-full of data at a time. Commented Feb 18, 2013 at 20:51
  • 1
    I don't think that's the first 2 chars - I think that's a single hex zero. You've looked at the underlying database table, right? The other file entries don't appear like that? (It's been a long time since I looked at binary data in a database!) Also, can you verify (through debugging) that binBYTES has a non-zero length? Commented Feb 18, 2013 at 22:19
  • 1
    Just for the heck of it, before creating the binary reader, insert the line stm.Position = 0;. See if that makes any difference. I'm wondering whether you're getting either an empty stream or a stream that has already been read through and is positioned at the end. Commented Feb 20, 2013 at 15:22

1 Answer 1

0

I was having the same problem, that is, the first time the image was saved correctly on the database side, but if subsequently validation failed and then I tried to save the image again after entering valid data I would get 0x in the image column. To solve that I did what @Ann L. said:

byte[] photo = null;

if(model.Photo != null)
{
    var stream = model.Photo.InputStream;
    stream.Position = 0;

    using(BinaryReader br = new BinaryReader(model.Photo.InputStream))
    {
        photo = br.ReadBytes(model.Photo.ContentLength);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.