MVC 4 Razor File Upload

2018-12-31 18:26发布

问题:

I am new to MVC 4 and I am trying to implement File Upload Control in my website. I am not able to find the mistake.I am getting a null value in my file.

Controller:

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\");
        }
    }

View:

@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:

The Upload method\'s HttpPostedFileBase parameter must have the same name as the the file input.

So just change the input to this:

<input type=\"file\" name=\"file\" />

Also, you could find the files in 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:

Clarifying it. Model:

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 Action

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);
  }
}

Finally the Extension method for checking the 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:

View Page

@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 file

$(document).on(\"click\", \"#btnid\", function (event) {
        event.preventDefault();
        var fileOptions = {
            success: res,
            dataType: \"json\"
        }
        $(\"#formid\").ajaxSubmit(fileOptions);
    });

In Controller

    [HttpPost]
    public ActionResult UploadFile(HttpPostedFileBase file)
    {

    }


回答4:

you just have to change the name of your input filed because same name is required in parameter and input field name just replace this line Your code working fine

 <input type=\"file\" name=\"file\" />


回答5:

I think, better way is use HttpPostedFileBase in your controller or API. After this you can simple detect size, type etc.

File properties you can find here:

MVC3 How to check if HttpPostedFileBase is an image

For example 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();  
}

Hope it help.