无法使用C#从asp.net的客户端接收文件

时间:2015-04-21 19:14:50

标签: c# asp.net image-uploading

我正在尝试从表单中获取个人资料图片。 html看起来像这样:

<form action="UpdateProfile.aspx" method="post">
  <input type='file' name='profilePic'/>
</form>

服务器端代码如下所示:

HttpPostedFile image = Request.Files["profilePic"];
string imagePath = @"../Pictures/Profile/DefaultPicture.png";
if (image.ContentLength >0 && image != null)
{
   if (Path.GetExtension(image.FileName) == "jpg" || Path.GetExtension(image.FileName) == "jpeg" ||
       Path.GetExtension(image.FileName) == "png" || Path.GetExtension(image.FileName) == "gif" ||
       Path.GetExtension(image.FileName) == "bmp")
   {
       string fileExtention = Path.GetExtension(image.FileName);
       string FileName = Session["Username"].ToString() + "." + fileExtention;
       image.SaveAs(Server.MapPath(Path.Combine("../Pictures/Profile/", FileName)));
       imagePath = Path.Combine("../Pictures/Profile/", FileName);
   }
}

但它永远不会奏效,无论我上传的image变量总是null。 它就像服务器无法接收它或其他东西。你能帮我解决一下,还是告诉我哪里出错了?先感谢您。

2 个答案:

答案 0 :(得分:3)

请务必正确设置内容类型:

  

仅在HTTP请求时填充文件集合   Content-Type值是“multipart / form-data”。

https://msdn.microsoft.com/en-us/library/system.web.httprequest.files%28v=vs.110%29.aspx

以下是一个例子:

<FORM action="..."
       enctype="multipart/form-data"
       method="post">
   ...
</FORM>

答案 1 :(得分:0)

指导你的一个例子。

 <asp:FileUpload ID="FileUpload1" runat="server" />
 <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />

 using System.IO;
 using System.Collections.Generic;
 protected void Upload(object sender, EventArgs e)
 {
    if (FileUpload1.HasFile)
    {
    string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
    FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Images/") + fileName);
    Response.Redirect(Request.Url.AbsoluteUri);
   }
 }