简体   繁体   中英

uploading image to server using HTML5.0 with c# backend

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM