Download Bank Image with ASP.NET MVC5

Asked

Viewed 161 times

2

I am saving images in the database in varbinary format.

byte[] arrayImagem = null;

using (MemoryStream memoryStream = new MemoryStream())
{
    novaSolicitacao.Anexos.InputStream.CopyTo(memoryStream);
    arrayImagem = memoryStream.ToArray();

    aberturaOcorrenciaDao.EnviaAnexosDaOcorrenciaSustentacao(Convert.ToString(numOcorrencia), 
        arrayImagem, novaSolicitacao.Anexos.FileName, novaSolicitacao.Anexos.ContentType, novaSolicitacao.IdSolicitante);

    arrayImagem = null;
}

But I’m not able to recover this image from the bank and make it available for download. Something very simple, an action that takes the result in varbinary of the database and mounts the image and returns with an action of type Fileresult.

My return would be something like this:

        public FileResult DownloadAnexoOcorrencia(string idArquivo)
    {
        var dao = new EditarOcorrenciaDAO();

        //Busca os bytes do arquivo no banco
        var arquivo = dao.BuscaAnexoEspecifico(idArquivo);

        //Aqui entra a função para converter esses bytes em imagem

        return File();
    }

Consultation of the DAO:

        public AnexosOcorrencia BuscaAnexoEspecifico(string id)
    {
        var select = dao.conexao.CreateCommand();
        select.CommandText = "select * from TB_Ocorrencia_Arquivo where idArquivo = @idArquivo";

        var paramIdOcorrencia = new SqlParameter("idArquivo", id);
        select.Parameters.Add(paramIdOcorrencia);

        var resultado = select.ExecuteReader();
        resultado.Read();

        var anexo = new AnexosOcorrencia();
        anexo.IdArquivo = Convert.ToString(resultado["idArquivo"]);
        anexo.IdOcorrencia = Convert.ToString(resultado["idOcorrencia"]);
        anexo.NomeArquivo = Convert.ToString(resultado["nmArquivo"]);
        anexo.TipoArquivo = Convert.ToString(resultado["TipoArquivo"]);

        anexo.Arquivo = (byte[])(resultado["Arquivo"]);


        resultado.Close();

        return anexo;
    }

View calling function in Controller:

 <div class="col-md-3">
            <label style="background-color: #eee;">Documentos anexados - Solicitante:</label>
            @*<input type="text" class="form-control input-sm" readonly value='@ViewBag.DadosOcorrencia.PosicaoTorre' />*@
            @foreach (var anexo in ViewBag.Anexos)
            {
                <div class="col-md-12 row" id="@anexo.IdArquivo">
                    <a onclick="DownloadArquivo(@anexo.IdArquivo)" style="cursor: pointer;">
                        <span>@anexo.NomeArquivo</span>
                    </a>
                </div>
            }
        </div>

<script type="text/javascript">

    function DownloadArquivo(value) {

        var urlDownload = '@Url.Action("DownloadAnexoOcorrencia", "EditarOcorrencia")';
        $.post(urlDownload, { idArquivo: value });
    }
</script>
  • Do you want to "force" the file to download? Enter your Return code for me to see how you are doing

  • I edited the question @Tiago. But I don’t know how to start mounting the image with rotated bytes from the bank.

  • Don’t just return the file stream, you need to set the mime-type.

  • your Return needs to look like this: Return File(.Filepath file, "image/jpeg", file.Filename);

  • What you keep in the "Type", you call the method BuscaAnexoEspecifico(string idArquivo) but presented code of BuscaAnexos(string id)?

  • The Search appendages(string id) code is the way to call the asynchronous form method in the View. It receives the file id to download.

  • And what does it return? a AnexosOcorrencia ??? ps.: There is nothing asynchronous in your code

  • I corrected the code of the call DAO, (I had copied the wrong code). And I entered the code of the view making the call asynchronous.

  • The return of the DAO "File" is where it contains the bytes to mount the image

Show 4 more comments

1 answer

0

Your controller DownloadAnexoOcorrencia is incomplete.

I made two examples of how you can get the result you want:

Example 1:

public FileStreamResult DownloadImagem()
{
    //Converter byte[] to Stream
    Stream streamImg = new MemoryStream(BuscarImagem());
    return File(streamImg, "image/png");
}

Example 2:

public FileContentResult DownloadImagem2()
{
    return File(BuscarImagem(), "image/png");
}

My examples are for PNG image, if you use other types check mime type.

My method BuscarImagem() not important. What you need to know is that it returns a byte[] which is the image you want to make available for download, equivalent to your method BuscaAnexoEspecifico().

I made an example and put it on Github.

References:

  1. https://docs.microsoft.com/pt-br/dotnet/api/system.web.mvc.filestreamresult?view=aspnet-mvc-5.2

  2. https://docs.microsoft.com/pt-br/dotnet/api/system.web.mvc.filecontentresult?view=aspnet-mvc-5.2

Browser other questions tagged

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