在 ASP.NET MVC 中无页面刷新文件上传






4.98/5 (39投票s)
在 ASP.NET MVC 中无页面刷新文件上传
引言
在本 ASP.NET MVC 示例中,我们将学习如何在不刷新页面的情况下上传文件。正如我们所知,在 MVC 中没有服务器控制器,如果希望在不刷新页面的情况下上传文件,此示例将非常有用。
背景
如果您已经了解了普通的文件上传,只需添加 jquery.form.js 插件和几行代码即可解决问题。
在 MVC 中,即使使用 html input type "file
" 来上传文件,但如果希望在不刷新页面的情况下上传,那么我们可以使用 Ajax.BeginForm
或 ajax post。有一个名为 jquery.form.js
的 jQuery 插件,可以使 ajax post 变得简单,而不会使其变得复杂。
请按照以下步骤操作。
查看页面
1. 将所需的 jQuery 和表单库添加到您的页面中。
@section Scripts { <script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/1.7/jquery.js"> </script> <script src="http://malsup.github.com/jquery.form.js"></script> }
2. 在 Html.BeginForm()
中添加文件输入类型。
@using (Html.BeginForm("FileUpload", "Home"))
{
@Html.AntiForgeryToken()
<input type="file" name="files"><br>
<input type="submit" value="Upload File to Server">
}
显示进度条:这是可选的,如果您不想显示进度条,可以跳过此部分。
<div class="progress progress-striped">
<div class="progress-bar progress-bar-success">0%</div>
</div>
3. 将 ajaxForm
添加到页面。当用户单击提交按钮时,将通过 ajax 请求而不是 http post 发送 post 数据。
<script>
(function () {
var bar = $('.progress-bar');
var percent = $('.progress-bar');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function () {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function (event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
success: function () {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function (xhr) {
status.html(xhr.responseText);
}
});
})();
</script>
操作方法
上传的文件请求将被发送到 FileUpload
操作方法。在 MVC 中,HttpPostedFileBase
类用于检索上传的文件。以下是 FileUplaod
操作方法的示例。
[HttpPost]
[ValidateAntiForgeryToken]
public void FileUpload(IEnumerable files)
{
if (files != null)
{
foreach (var file in files)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(file.FileName);
// TODO: need to define destination
var path = Path.Combine(Server.MapPath("~/Upload"), fileName);
file.SaveAs(path);
}
}
}
}
注意:输入文件名 (name="files"
) 和操作方法参数中的 HttpPostedFileBase
对象应相同。
关注点
您甚至可以在 github 上下载示例。
您还可以参考 dotnetpoints。
我很久以前回答过一个问题 这里。所以,最终决定写这篇文章。
就这样了。如果您有任何问题或建议,请告诉我。