我的wwwroot文件夹中有一些文件。我想写一个代码,用户点击输入按钮并下载他想要的文件。所以在用户选择文件之前,文件名是未知的。
我写了这个代码:
配置文件控制器:
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"}
};
}
我的视图组件:
<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>
当我点击下载按钮时,什么也没发生。在跟踪代码中,我没有发现任何问题。文件名正确发送到操作。我认为这是ajax方法的问题。但我找不到。有人能帮我吗?
注意:如果文件名是已知的,用下面的代码替换为input标记,我就可以下载已知的文件。
<a asp-action="Download" asp-controller="Profile" asp-route-filename="1.pdf"> download </a>
正如我在评论中提到的,我只需要更改javascript代码。它适用于Chrome和Edge
<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,
},
success: function (data) {
var a = document.createElement('a');
var url = window.URL.createObjectURL(data);
a.href = url;
a.download = 'myfile.pdf';
document.body.append(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
}
});
}
});
});
</script>