I can not open a byte array extracted from the database!

2

Language: C # / ASP.NET

Database: PostgreeSQL

Component used to upload the file: FileUpload

The following is the component:

Hereisthemethodtoinsertatableinthedatabasethatonlyhasthefields:

attachment_id/attachment_name/attachment

Andfinallythemethodtoopenthefile:

And the result of this method is:

In this example I uploaded a .jpg image and it gave me this result error. I am not able to recover any files.

What's wrong with my methods, I still can not visualize ... Thank you.

    
asked by anonymous 16.04.2015 / 16:38

1 answer

1

The problem occurs because you are not writing the contents of the file correctly.

By its code, the Attachment property of the AnexoBLL class is of 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 internally use the .ToString () method of type 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[]')

Correct would be the use of parameters, not only for the code to work, but because it is a good practice and avoids even SQL injection problems. To enter, 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 assuming you're using the correct type in your column, which in this case should be bytea (see more at

18.04.2015 / 21:57