Provide file download from server

3

There is a feature to register the data of a client. The user selects a file from his computer, and this file is imported into the server into a separate folder, which can be a PDF , JPEG PNG .

There is an editing screen for this client, where they will have a button to download this document. My question is: How to implement the download functionality of the file stored on the server?

    
asked by anonymous 26.04.2017 / 18:40

3 answers

6

So:

public FileResult Download(int id)
{
    var caminhoDaImagem = /* Aqui você usa id que vem por parâmetro pra fazer alguma operação que seleciona o caminho da imagem de algum lugar */
    byte[] dadosArquivo = System.IO.File.ReadAllBytes(caminhoDaImagem);
    return File(dadosArquivo, System.Net.Mime.MediaTypeNames.Image.Jpeg, "meuarquivo.jpg");
}

See here the MediaTypes for natively available images .

Usage:

http://localhost:porta/MeuController/Download/1
    
26.04.2017 / 19:58
5

If the file exists on disk and you know its path, it would be better to return it without having to worry about opening it, right?

public FileResult Download(int id) 
{
    string caminho = /*Buscar caminho do arquivo */;
    var result = new FilePathResult(caminho, "image/jpeg")
    {
        FileDownloadName = "nomeParaDownload.jpg"
    };

    return result;
}
    
26.04.2017 / 20:46
4

You should have already seen that the methods of the controllers that meet the requests of the pages return objects of type ActionResult .

Normally you return HTML content through the View method of the controller itself. You can change the return type to a file easily, just return a FileStreamResult object instead of calling the View method.

The official documentation .

And an example:

public ActionResult BoloDeFuba()
{
    FileStream arquivo = new FileStream(@"c:\bolo de fubá.doc");
    FileStreamResult download = new FileStreamResult(arquivo, "application/msword"); // O segundo parâmetro é o Mime type
    download.FileDownloadName = "bolo de fubá.doc";
    return download;
}

Note that FileStreamResult receives any object of type Stream . You can mount a file in memory or load it from the database instead of loading from a folder, when you need it or more convenient.

    
26.04.2017 / 19:17