1

I am trying to build an image application in which user can upload an image on the server.

I am using HTML 5.0 as my front end and c# as my backend following an MVC 4 architecture. I will be attaching my code below.

    <div id="imageup">
    <form method="post" action="UploadImage" enctype="multipart/form-data">
    <label for="file">Filename:</label>
    Image: <input type="file" name="file" id="file"/>
    NAME: <input type="text" name ="testname" id="nametestid" runat="server"/>
    <input type="submit" value="image" />


    </form>

    </div>

Here is my backend code which I found on http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx

Here is the back end code:

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult UploadImage(String testname)
    {
        Console.Out.WriteLine("HERE");
       // name.Length
       if(testname.Length==0){
          System.Console.WriteLine("Hello");
           //return Json("All files have been successfully stored.");
       }

       foreach (string file in Request.Files)
       {
           HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
           if (hpf.ContentLength == 0)
               continue;
           string savedFileName = Path.Combine(
              AppDomain.CurrentDomain.BaseDirectory,
              Path.GetFileName(hpf.FileName));
           hpf.SaveAs(savedFileName);
       }
       /* foreach (HttpPostedFile file in files)
        {
            string filePath = Path.Combine(TempPath, file.FileName);
            System.IO.File.WriteAllBytes(filePath, ReadData(file.InputStream));
        }

        //*/
        return RedirectToAction("Create");

    }

The issue with the code is when I pass file by browser, and in breakpoints I get the value of image as null, but I am getting the text which I have inputted in the same form as data.

2
  • Since this is MVC - get rid of the runat="server" on your name input element. Also, make the name and id attibutes match and try again. Commented Feb 7, 2014 at 21:46
  • I have the same id and name as file, and for text it is different, but I am able to get the text that I enter in the text box. When I set breakpoints I can see text but the file count is 0. Commented Feb 7, 2014 at 21:52

1 Answer 1

1

Finally figured it out,

The point was to tell the controller that I am passing the image as part of form.

just had to add:

@using (Html.BeginForm("UploadImage", "Image", FormMethod.Post,
                        new { enctype = "multipart/form-data" }))

Thanks Mike & Tommy

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.