I am unable to open a byte array extracted from the database!

Asked

Viewed 386 times

2

Language: C#/ASP.NET

Database: Postgreesql

Component used for file upload: Fileupload


Below is the component:

fileUpload

Below is the method to perform the insertion to a table in the database that only has the fields:

id_attachment / attachment / attachment

inserir a descrição da imagem aqui inserir a descrição da imagem aqui

And finally the method to open the file:

inserir a descrição da imagem aqui

And the result of this method is:

inserir a descrição da imagem aqui

In this example I uploaded an image . jpg and gave me this result error. I am unable to recover any files.

What’s wrong with my methods, I still can’t visualize... Grateful.

  • If you are opening a file, why are you using File.WriteAllBytes()? It would not be the case to read the file, and not write?

  • I don’t think so. I already have this file inside my database in Bytea(Byte[]) what I want now is to write it again (transforms it from byte[] to .jpg) to open.

1 answer

1

The problem is because you are not recording the file contents properly.

By your code, the property Annex class Anexobll is of the type byte[]. At the point in the code you create the SQL string that will be executed in the database, you are simply concatenating the byte[] property with a string. This will not cause the property value to be used, but the framework will use the method internally. Tostring() byte[], which will return the type name. Soon your query would look something like:

insert into tb_anexo (nome_arquivo, anexo) values ('imagem.jpg', 'System.Byte[]')

The correct thing would be to use parameters, not only for the code to work, but because it is good practice and avoids even security problems (SQL Injection). To insert, use the code as follows (adapt to use your connection):

Npgsql.NpgsqlCommand command = new Npgsql.NpgsqlCommand();
command.CommandText = "insert into tb_anexo (nome_arquivo, anexo) values (:nome_arquivo, :anexo)";
command.Parameters.AddWithValue("nome_arquivo", anexo.NomeArquivo);
command.Parameters.AddWithValue("anexo",NpgsqlDbType.Bytea, anexo.Arquivo);
command.ExecuteNonQuery();

I’m guessing you’re using the correct type in your column, which in this case should be bytea (see more in http://www.postgresql.org/docs/9.0/static/datatype-binary.html)

  • 1

    Thank you very much for your clarification Marcus! I had already changed the code before I saw your post for this mode, but it was good to know that it is good practice. However my problem now is that I am not managing to recover this byte from the bank. When I try to recover it returns me null. Can help me/

  • When you run the query directly in the database, what do you see? Is the attached column null or not? Could you show the code that reads the table? Is using Datareader?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.