How to return a file to the client?

Asked

Viewed 30 times

0

I need to return a file in my action so that the client can download it. In my current code, the file is being saved on server.

[HttpGet]
public JsonResult ExibirPrintRPA(int? id)
{
    string _nameFile = string.Empty;
    EmissaoPrintRPA lemissao = new EmissaoPrintRPA();
    EmissaoPrintRPA emissaoPrints = _EmissaoPrintRPAApplicationService.GetById(lemissao);           
    var _imagem = emissaoPrints.ST_IMAGEM;
    _imagem = _imagem.Replace(" ", "+");
    int mod4 = _imagem.Length % 4;
    if (mod4 > 0)
    {
        _imagem += new string('=', 4 - mod4);
    }

    var _img = Convert.FromBase64String(_imagem);
    var _filePath = string.Format("{0}\\{1}.{2}", 
        Server.MapPath("~/Files/Downloads"), _nameFile, "jpeg");
    using (var fs = new FileStream(_filePath, FileMode.Create))
    {
        fs.Write(_img, 0, _img.Length);                
        fs.Flush();               
    }

    return Json(new 
    { 
        file = string.Format("{0}.{1}", _nameFile, "jpeg"), 
        path = _filePath 
    });
}
  • Who defines where the file is saved is the client, you cannot control it by the server.

  • @LINQ, yes I understand but the way the code posted the file is being saved in the project folder, there in the Server and not saved in the user’s machine.

  • Ah, wow, that’s not what you meant by reading the question. You’re using ASP.NET Core?

  • No, I’m using ASP.net MVC

1 answer

0


Instead of trying to salvage a file, you need to return that file to the caller of your action.

This can be done using the method File().

I don’t quite understand this manipulation you made before Convert.FromBase64String, but I’m assuming she’s right.

As the method Convert.FromBase64String already returns a array of bytes, you can simply pass it to the method File.

Note that you need to inform as the second parameter the content type of the file and, as the third parameter, its name.

[HttpGet]
public ActionResult ExibirPrintRPA(int? id)
{
    string _nameFile = string.Empty;

    EmissaoPrintRPA lemissao = new EmissaoPrintRPA();
    EmissaoPrintRPA emissaoPrints = _EmissaoPrintRPAApplicationService.GetById(lemissao);           

    var _imagem = emissaoPrints.ST_IMAGEM;
    _imagem = _imagem.Replace(" ", "+");

    int mod4 = _imagem.Length % 4;

    if (mod4 > 0)
    {
        _imagem += new string('=', 4 - mod4);
    }

    var bytesImagem = Convert.FromBase64String(_imagem);

    return File(bytesImagem, "ContentTypeArquivo", "NomeArquivo");
}
  • is giving error in the last line: return File(, 'cause in my case I’m wearing a JsonResult and not a ActionResult,

  • 1

    You will have to change the return type _(ツ)_/ . You want to return a file and not a JSON, so the return will be of the type FileContentResult (ActionResult works because it’s the most abstract type).

Browser other questions tagged

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