2014-02-07 33 views
1

我想建立一个图像应用程序,用户可以在其中上传图像的服务器上。上传图像到服务器使用HTML5.0与c#后端

我使用HTML 5.0作为我的前端,c#作为我的后端遵循MVC 4架构。我将在下面附上我的代码。

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

这里是我的后端代码,我在http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx

发现这里是后端代码:

[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"); 

    } 

与代码的问题是,当我通过浏览器传递文件,并在断点我得到的图像的值为空,但我得到的文本,我已经输入与数据相同的形式。

+0

由于这是MVC - 获取'你的名字输入元素上摆脱了'RUNAT = “服务器” 的。另外,使'name'和'id'属性匹配并重试。 – Tommy

+0

我的文件名与文件名相同,文本也不同,但我可以在文本框中输入文本。当我设置断点时,我可以看到文本,但文件数量为0。 –

回答

1

终于想通了,

的一点是要告诉大家,我传递的图像形式的一部分的控制器。

刚补充:

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

感谢迈克&汤米