查看这篇 Scott Hanselman 文章的底部。他基本上演示了如何将有关文件上传状态的信息发送回用户。特别是,他创建了一个 ViewModel 来保存 fileUpload 结果,根据每个文件的上传状态创建一个结果列表,然后通过将信息传递给要呈现的 View 将信息发送回用户。
http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx
编辑:
如果您希望在上传时提示用户确认(如果文件已经存在),您可以:
(a) 使用 javascript ajax 调用来检查文件是否存在并在发布之前提示用户 - 或 -
(b) 允许用户提交,将文件保存到临时位置,在另一个视图中提示用户确认,如果用户确认则处理文件。
示例 (a):
[控制器]
public ActionResult AddFileForm() {
return View();
}
[HttpPost]
public ActionResult AddFileX(IEnumerable<HttpPostedFileBase> files) {
// do what you need to save your files and/or update your db
foreach (var file in files) {
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
}
// collect the updated file ids and send to View to render (should prob use Strongly typed class(es))
string[] results = {"123", "456", "789"};
return View(results);
}
[HttpPost]
public JsonResult FileExists(List<string> filelist) {
//check if file(s) exist given filename
// return ids for files that already exist on your system
string[] results = {"123", "", "789"};
return Json(results);
}
[查看] AddFileForm
@using (Html.BeginForm("AddFileX", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input id="f1" type="file" name="files" multiple="true" />
<input id="f2" type="file" name="files" multiple="true" />
<input id="overwrite" type="hidden" value="false" />
<input id="submit" type="submit" value="Upload" />
}
<script>
$(document).ready(function () {
$('#submit').click(function (e) {
if ($('#overwrite').val() == 'true')
return; //proceed w/ submit
e.preventDefault();
// collect filenames of proposed file updates
var files = [];
$('input[type=file]').each(function () {
var filename = $(this).val();
files.push(filename);
});
// send request to check if files exist
$.ajax({
type: "POST",
url: "/File/FileExists",
data: { filelist: files },
success: function (data) {
confirmUpload(data);
},
traditional: true
});
});
});
function confirmUpload(results) {
var existing = false;
$(results).each(function () {
var fid = $(this)[0];
if (fid.length > 0) {
existing = true; //file exists on Server, fid returned.
//do stuff..highlight table row..etc
}
});
if (existing) {
//do whatever to request confirmation, show a message div, etc
var answer = confirm("Overwrite files?");
if (answer) {
// if confirmed, set flag submit form
$('#overwrite').val('true');
$('#submit').click(); //$('form').submit() - unreliable
}
}
}
</script>
希望这能给你一些想法。