views:

72

answers:

2

Hi, I am trying to download a file I have uploaded to an image field in my MS-SQL database. The problem is that when I try to open the file it just says System.Byte[] instead of containing the actual content.

UploadFiles is my class which contains the filename, id, filedata etc.

public void DownloadUploadedFile(Page sender, UploadFiles uf)
{
    sender.Response.Clear();
    sender.Response.ContentType = uf.FileType; 
    sender.Response.AddHeader("Content-Disposition",
        "attachment; filename=" + uf.FileName);
    sender.Response.BinaryWrite(uf.FileData); // the binary data
    sender.Response.End();
}

Here I retrieve the data from my database:

 while (reader.Read())
                    {
                        UploadFiles uf = new UploadFiles();
                        uf.FileData = encoding.GetBytes(reader["filedata"].ToString());
                        uf.FileName = reader["name"].ToString();
                        uf.FileType = reader["filetype"].ToString();
                        uf.FileId = Convert.ToInt32(reader["id"]);
                        return uf;
                    }
A: 

Try uf.FileName.ToString(), otherwise you're getting the object type, not the FileName property text.

Darth Continent
uf.FileName is a property on my class which contains the filename. I have debugged it and it returns test.txt. Also as I mentionen UploadFiles has nothing to do with the asp upload file control, but is my own class containing the properties.
Dofs
+2  A: 

The

uf.FileData = encoding.GetBytes(reader["filedata"].ToString());

should be

uf.FileData = (byte[])reader["filedata"];

The data returned is a byte array, and you call ToString() on the byte array, which just defaults to returning the class name (system.byte[]) - which you then convert to a byte array. It should just be cast right away

Pete
Of course you should check for NULL first, which is returned as DbNull.Value, if the field can have null values.
Pete
Thank you very much it worked! Never thought that it could be the encoding when retrieving the files.The database field doesn't allow null types, so in this case it is not necessary.
Dofs