3
In my Asp.Net MVC 4 project, I have a View with a button and the following script:
<input type="button" value="Teste" id="baixarArquivo" />
<script>
(function () {
$("#baixarArquivo").off("click").on("click", function () {
DownloadArquivo();
});
function DownloadArquivo() {
$.ajax({
beforeSend: function () {
// Inicia Load
},
complete: function () {
// Finaliza Load
},
contentType: 'application/json, charset=utf-8',
dataType: 'json',
type: 'POST',
url: '@Url.Action("DownloadArquivo", "MeuController", new { area = "Administrador" })',
// Parâmetros
//data: JSON.stringify(
// {
// Param1: minhaVar,
// }),
success: function (data) {
if (data.success) {
// Baixar arquivo
} else {
alert("Erro! " + data.title + " " + data.error);
}
},
fail: function () {
alert("Error 007");
}
});
}
})();
</script>
In the Controller my Action is as follows:
[HttpPost]
public ActionResult DownloadArquivo()
{
try
{
byte[] fileBytes = null;
using (MemoryStream ms = new MemoryStream())
{
using (TextWriter tw = new StreamWriter(ms))
{
tw.WriteLine("Este é apenas um teste!");
tw.Flush();
ms.Flush();
fileBytes = ms.ToArray();
}
}
return Json(new
{
success = true,
content = fileBytes,
fileName = "meuArquivo",
mimeType = System.Net.Mime.MediaTypeNames.Text.Plain
}, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new
{
success = false,
error = ex.Message,
title = "Download"
}, JsonRequestBehavior.AllowGet);
}
}
How to download the file if everything goes well?
In the Success of the call from
ajax
, make aconsole.log(data);
, see if you print something.– Miguel