@{
ViewBag.Title = "Home Page";
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body id="linkContainer">
<input type="file" id="fileUpload" />
<button type="button" onclick="upload()">上傳</button>
@Html.ActionLink("Download Excel", "Download", "Home", new { }, new { @class = "btn btn-primary" })
<script>
// 用於在 JavaScript 中設置 URL
const uploadUrl = '@Url.Action("UploadFile", "Home")';
function upload() {
let fileUpload = document.getElementById("fileUpload");
let file = fileUpload.files[0];
if (!file) {
alert("請選擇檔案");
return; // 如果沒有選擇檔案,終止上傳
}
let formData = new FormData();
formData.append("file", file);
$.ajax({
type: 'POST',
url: uploadUrl,
data: formData,
processData: false,
contentType: false,
success: function (response) {
if (response.success) {
// 创建一个下载链接
var downloadLink = $('<a></a>')
.attr('href', response.fileUrl)
.attr('download', file.name) // 设置为下载并指定文件名
.text('Download File');
// 添加链接到页面
$('#linkContainer').html(downloadLink);
// 模拟点击下载链接
downloadLink[0].click();
} else {
alert("文件上傳失敗!");
}
},
error: function (xhr, status, error) {
alert(status + ' ' + error);
}
});
}
</script>
</body>
</html>
<a href="/Home/DownloadExcel" class="btn btn-primary">Download Excel</a>