http://stackoverflow.com/questions/19042116/ajax-beginform-in-mvc-to-upload-files
*****************************************************************************
签名档: http://feiyun0112.cnblogs.com/
*****************************************************************************
签名档: http://feiyun0112.cnblogs.com/
Request.Files[upload]是获取字符串的public PartialViewResult Files(HttpPostedFileBase file)
{
IEnumerable<string> files;
if ((file != null) && (file.ContentLength > 0))
{
string fileName = file.FileName;
string saveLocation = @"D:\Files";
string fullFilePath = Path.Combine(saveLocation, fileName);
try
{
file.SaveAs(fullFilePath);
FileInfo fileInfo = new FileInfo(fullFilePath);
file.InputStream.Read(new byte[fileInfo.Length], 0, file.ContentLength);
}
catch (Exception e)
{
TempData["FileUpload"] = e.Message;
return PartialView();
}
files = Directory.GetFiles(@"D:\Files\");
return PartialView(files);
}
else
{
files = Directory.GetFiles(@"D:\Files\");
return PartialView(files);
}
}
{
@Html.AntiForgeryToken();
<input type="file" name="file1" /> <br />
<input type="submit" value="上传" />
}
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div><div id="status"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function () { var bar = $(".bar");
var percent = $(".percent");
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>Controller: //分步视图上传文件 [HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Files()
{
HttpPostedFileBase file = Request.Files[0];
if (file != null)
{ // 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); }
}
ViewBag.file = Path.GetFileName(file.FileName);
return PartialView();
}
}Files.cshtml<ul> <li>@ViewBag.file</li></ul>运行效果图: