MVC 4 Razor File Upload
Sou novo no MVC 4 e estou a tentar implementar o controlo de Upload de ficheiros em
o meu site. Não consigo encontrar o erro.Estou a ficar nula.
valor no meu ficheiro.
Controlador:
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");
}
}
ver:
@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" />
}
217
5 answers
O parâmetro Upload
do método HttpPostedFileBase
deve ter o mesmo nome que o file input
.
Então muda a entrada para isto:
<input type="file" name="file" />
Além disso, você pode encontrar os arquivos em 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");
}
284
Author: Cristi Pufu, 2014-01-22 17:31:11
A clarificá-la.
Modelo:
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; }
Após A Acção
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);
}
}
Finalmente o método de extensão para verificar o ficheiro 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;
}
}
}
60
Author: Bishoy Hanna, 2015-11-24 16:33:27
Ver Página
@using (Html.BeginForm("ActionmethodName", "ControllerName", FormMethod.Post, new { id = "formid" }))
{
<input type="file" name="file" />
<input type="submit" value="Upload" class="save" id="btnid" />
}
Ficheiro do Programa
$(document).on("click", "#btnid", function (event) {
event.preventDefault();
var fileOptions = {
success: res,
dataType: "json"
}
$("#formid").ajaxSubmit(fileOptions);
});
No Controlador
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
}
16
Author: Jagadisha B S, 2014-10-15 05:00:11
Você só tem que mudar o nome da sua entrada arquivada porque o mesmo nome é necessário no parâmetro e no nome do campo de entrada apenas substitua esta linha o seu código a funcionar bem
<input type="file" name="file" />
6
Author: Hafiz Asad, 2016-03-04 11:38:43
Acho que a melhor maneira é usarO HttpPostedFileBase no seu controlador ou na API. Depois disso você pode detectar simples tamanho, tipo etc.
Propriedades do ficheiro que pode encontrar aqui:
MVC3 como verificar se o HttpPostedFileBase é uma imagem
Por exemplo 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();
}
Espero que ajude.
2
Author: Petr Tomášek, 2017-05-23 12:34:39