我一直在建立一个网站,并尝试在我的注册页面添加一个字段,用户可以上传自己的个人资料照片。我打算将给定的照片保存到项目中的文件夹中,但无法弄清楚为什么我会继续获得NullReferenceException
。
protected void Page_Load(object sender, EventArgs e)
{
string gender, Fname, Lname, username, pass, Sorientation, country;
if (Request.Form["sub"] != null)
{
HttpPostedFile profile;
profile = Request.Files["profile-image"];
string FileName = System.IO.Path.GetFileName(profile.FileName);
profile.SaveAs(Server.MapPath(System.IO.Path.Combine("D:/.... /Profiles/", FileName))); `
}
//..
}
const realFileBtn = document.getElementById("profile-image");
const customBtn = document.getElementById("custom-button");
const customTxt = document.getElementById("custom-text");
customBtn.addEventListener("click", function () {
realFileBtn.click();
});
realFileBtn.addEventListener("change", function () {
if (realFileBtn.value) {
customTxt.innerHTML = realFileBtn.value.match(
/[\/\\]([\w\d\s\.\-\(\)]+)$/
)[1];
} else {
customTxt.innerHTML = "No image was chosen. Profile will be set as default!";
}
});
<input type="file" id="profile-image" name="profile-image" hidden="hidden" accept=".gif,.jpg,.jpeg,.png,.BMP" />
<button type="button" id="custom-button" style=" padding: 4px;
color: transparentize( rgba(255,255,255,1),0.8 );
background-color: rgb(255, 96, 207);
border-radius: 10px;
cursor: pointer;">Upload custom image </button>
<br />
<span id="custom-text">No image was chosen. Profile will be set as default!</span>
我猜您的表单翻译如下:
确保你有enctype
作为multipart/form-data
<form action="enter path" method="post" enctype="multipart/form-data">
<input type="file" id="profile-image" name="profile-image" hidden="hidden" accept=".gif,.jpg,.jpeg,.png,.BMP" />
<button type="submit" >Submit</button>
</form>
进行空检查以避免NullReferenceException
if (Request.Files.Count > 0)
{
HttpPostedFileBase profile;
profile = Request.Files[0];
if (profile != null && profile.ContentLength > 0)
{
var fileName = Path.GetFileName(profile.FileName);
profile.SaveAs(Server.MapPath(Path.Combine("D:/.... /Profiles/", fileName)));
}
}
您需要使用asp:FileUpload
控件而不是<input type="file" />
才能根据请求获取发布的文件。
<asp:FileUpload id="ProfileImage" runat="server" id="profile-image" name="profile-image" hidden="hidden" accept=".gif,.jpg,.jpeg,.png,.BMP" />
然后您可以通过ProfileImage
控件访问上传的文件
protected void Page_Load(object sender, EventArgs e)
{
//..
//check if user sent a file
if (ProfileImage.HasFile)
{
HttpPostedFile profile = ProfileImage.PostedFile;
string FileName = System.IO.Path.GetFileName(profile.FileName);
profile.SaveAs(Server.MapPath(System.IO.Path.Combine("D:/.... /Profiles/", FileName)));
}
//..
}