Загрузка файла Razor MVC 4
Я новичок в 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" />
}
Ответы
Ответ 1
Параметр Upload
HttpPostedFileBase
должен иметь то же имя, что и file input
.
Итак, просто измените ввод на это:
<input type="file" name="file" />
Кроме того, вы можете найти файлы в Request.Files
:
[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");
}
Ответ 2
Уточнение.
Модель:
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; }
Действия с сообщением
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
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;
}
}
}
Ответ 3
Страница просмотра
@using (Html.BeginForm("ActionmethodName", "ControllerName", FormMethod.Post, new { id = "formid" }))
{
<input type="file" name="file" />
<input type="submit" value="Upload" class="save" id="btnid" />
}
script файл
$(document).on("click", "#btnid", function (event) {
event.preventDefault();
var fileOptions = {
success: res,
dataType: "json"
}
$("#formid").ajaxSubmit(fileOptions);
});
В контроллере
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
}
Ответ 4
вам просто нужно изменить имя вашего входного файла, потому что одно и то же имя требуется в имени параметра и имени ввода
просто замените эту строку. Ваш код работает нормально
<input type="file" name="file" />
Ответ 5
Я думаю, лучший способ - использовать HttpPostedFileBase в вашем контроллере или API. После этого вы можете просто определить размер, тип и т.д.
Свойства файла вы можете найти здесь:
MVC3 Как проверить, является ли 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();
}
Надеюсь, что это поможет.