我是razor视图引擎的新手。我陷入了一种情况,我想上传一个带有图像浏览器的Change事件的Image。 Jquery函数如下:
$("#billUpload").change(function (){
$('#uploadImageForm').submit();
}
Razor视图代码如下:
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "uploadImageForm" }))
{
<span class="file-input btn btn-sm btn-default btn-file">
Browse…
<input id="billUpload" name="File" type="file">
</span>
}
Controller的代码在这里:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file == null)
{
ModelState.AddModelError("File", "Please Upload Your file");
}
else if (file.ContentLength > 0)
{
int MaxContentLength = 1024 * 1024 * 4; //Size = 4 MB
string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
if (!AllowedFileExtensions.Contains
(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
{
ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
}
else if (file.ContentLength > MaxContentLength)
{
ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
}
else
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/images/Bill/"), fileName);
file.SaveAs(path);
ModelState.Clear();
ViewBag.Message = "File uploaded successfully. File path : ~/Content/image/Bill/" + fileName;
}
}
}
return Json("Done",JsonRequestBehavior.AllowGet);
}
现在整个代码运行没有上传图像的问题,但我无法理解如何在警告框中显示控制器返回的这个json消息。提前谢谢。
答案 0 :(得分:4)
您可以像使用ajax
一样执行此操作。希望这会有所帮助。
$("#billUpload").on('change', (function(e) {
e.preventDefault;
var formData = new FormData($('#uploadImageForm')[0]);
$.ajax({
url : "/Home/Upload",
type : "POST",
data : formData,
cache : false,
contentType : false,
processType : false,
success : function(data) {
alert(data);
}
});
}));