Uploading image in ASP.NET MVC

前端 未结 2 807
小鲜肉
小鲜肉 2020-12-02 14:20

I have a Upload form and I want to pass my information such as an Image and some other field but I don\'t know how can I upload Image ..

this is my controller code :

相关标签:
2条回答
  • 2020-12-02 14:53

    Firstly, you'll need to change your view to include the following:

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

    Then you'll need to change your post ActionMethod to take a HttpPostedFileBase, like so:

    [HttpPost]
    public ActionResult Create(tblPortfolio tblportfolio, HttpPostedFileBase file)
    {
        //you can put your existing save code here
        if (file != null && file.ContentLength > 0) 
        {
            //do whatever you want with the file
        }
    }
    
    0 讨论(0)
  • 2020-12-02 15:00

    You can get it from Request using Request.Files Collection, In case of single file upload just read from the first index using Request.Files[0]:

    [HttpPost]
    public ActionResult Create(tblPortfolio tblportfolio) 
    {
     if(Request.Files.Count > 0)
     {
     HttpPostedFileBase file = Request.Files[0];
     if (file != null) 
     { 
      // business logic here  
     }
     } 
    }
    

    In case of Multiple files uploading, you have to iterate on the Request.Files collection:

    [HttpPost] 
    public ActionResult Create(tblPortfolio tblportfolio)
    { 
     for(int i=0; i < Request.Files.Count; i++)
     {
       HttpPostedFileBase file = Request.Files[i];
       if (file != null)
       {
        // Do something here
       }
     }
    }
    

    If you want to upload file without page refresh via ajax then you can use this article which uses jquery plugin

    0 讨论(0)
提交回复
热议问题