[英]Can't receive files from client side in asp.net using C#
I'm trying to get a profile image from a form. 我正在尝试从表单获取个人资料图像。 The html looks like this: html看起来像这样:
<form action="UpdateProfile.aspx" method="post">
<input type='file' name='profilePic'/>
</form>
The server side code looks like this: 服务器端代码如下所示:
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);
}
}
But it never works, no matter what I upload the image
variable is always null
. 但是它永远都行不通,无论我上传什么image
变量始终为null
。 its like the server cant recive it or something. 就像服务器无法接收它一样。 can you guys help me solve it or tell me where i went wrong? 你们可以帮助我解决问题或告诉我哪里出问题了吗? Thank you in advance. 先感谢您。
Be sure that you set the Content-Type correctly: 确保正确设置Content-Type:
The file collection is populated only when the HTTP request Content-Type value is "multipart/form-data". 仅当HTTP请求的Content-Type值为“ multipart / form-data”时,才会填充文件集合。
https://msdn.microsoft.com/en-us/library/system.web.httprequest.files%28v=vs.110%29.aspx https://msdn.microsoft.com/zh-cn/library/system.web.httprequest.files%28v=vs.110%29.aspx
Here is an example: 这是一个例子:
<FORM action="..."
enctype="multipart/form-data"
method="post">
...
</FORM>
An example to guide you. 指导您的示例。
<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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.