I have some files in my wwwroot folder. I want to write a code that user click on input button and download file that he wants. So filename is unknown until user select his file.
I wrote this code:
Profile Controller:
public async Task<IActionResult> Download(string filename)
{
if (filename == null)
return Content("filename not present");
var path = Path.Combine(
Directory.GetCurrentDirectory(),
"wwwroot", filename);
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, GetContentType(path), Path.GetFileName(path));
}
private string GetContentType(string path)
{
var types = GetMimeTypes();
var ext = Path.GetExtension(path).ToLowerInvariant();
return types[ext];
}
private Dictionary<string, string> GetMimeTypes()
{
return new Dictionary<string, string>
{
{".txt", "text/plain"},
{".pdf", "application/pdf"},
{".doc", "application/vnd.ms-word"},
{".docx", "application/vnd.ms-word"},
{".xls", "application/vnd.ms-excel"},
{".png", "image/png"},
{".jpg", "image/jpeg"},
{".jpeg", "image/jpeg"},
{".gif", "image/gif"},
{".csv", "text/csv"}
};
}
My view component :
<form>
<div class="form-group">
<label> Code : </label>
@Html.DropDownList("TopCode", null, htmlAttributes: new { @class ="form-control" })
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#download').click(function () {
{
var fName = $("#TopCode option:selected").val().toString();
var _url = '@Url.Action("Download", "Profile")';
$.ajax({
type: "POST",
url: _url,
xhrFields: {
responseType: 'blob'
},
data: {
filename: fName,
},
});
}
});
});
</script>
<div class="form-group">
<input id="download" type="button" value=" download "/>
</div>
</form>
when I clicked on download button, nothing happened. In tracing code, I don't find any problem. File name send to action correctly. I think It's a problem from ajax method. but I don't find it. Can someone help me?
Note: If file name was known , with this following code that replace with input tag, I could download the known file.
<a asp-action="Download" asp-controller="Profile" asp-route-filename="1.pdf"> download </a>