我是新的MVC 4,我试图实现文件上传控制在
我的网站。我找不到错误所在。我得到一个null
值。
控制器:
public class UploadController : BaseController
{
public ActionResult UploadDocument()
{
return View();
}
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path);
}
return RedirectToAction("UploadDocument");
}
}
观点:
@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="FileUpload" />
<input type="submit" name="Submit" id="Submit" value="Upload" />
}
我认为更好的方法是在你的控制器或API中使用HttpPostedFileBase。在此之后,您可以简单地检测尺寸,类型等。
你可以在这里找到文件属性:
如何检查HttpPostedFileBase是否是一个图像
例如ImageApi:
[HttpPost]
[Route("api/image")]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
try
{
string path = Path.Combine(Server.MapPath("~/Images"),
Path.GetFileName(file.FileName));
file.SaveAs(path);
ViewBag.Message = "Your message for success";
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
else
{
ViewBag.Message = "Please select file";
}
return View();
}
希望能有所帮助。
Upload方法的HttpPostedFileBase参数必须与文件输入具有相同的名称。
所以只要把输入改成这样:
<input type="file" name="file" />
此外,您可以在Request中找到这些文件。文件:
[HttpPost]
public ActionResult Upload()
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path);
}
}
return RedirectToAction("UploadDocument");
}
视图页面
@using (Html.BeginForm("ActionmethodName", "ControllerName", FormMethod.Post, new { id = "formid" }))
{
<input type="file" name="file" />
<input type="submit" value="Upload" class="save" id="btnid" />
}
脚本文件
$(document).on("click", "#btnid", function (event) {
event.preventDefault();
var fileOptions = {
success: res,
dataType: "json"
}
$("#formid").ajaxSubmit(fileOptions);
});
在控制器
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
}
澄清。
模型:
public class ContactUsModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public HttpPostedFileBase attachment { get; set; }
Post操作
public virtual ActionResult ContactUs(ContactUsModel Model)
{
if (Model.attachment.HasFile())
{
//save the file
//Send it as an attachment
Attachment messageAttachment = new Attachment(Model.attachment.InputStream, Model.attachment.FileName);
}
}
最后是检查hasFile的Extension方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AtlanticCMS.Web.Common
{
public static class ExtensionMethods
{
public static bool HasFile(this HttpPostedFileBase file)
{
return file != null && file.ContentLength > 0;
}
}
}