尝试上传aspx / c#文件时出错
本文关键字:文件 出错 aspx | 更新日期: 2023-09-27 18:16:56
我有以下c#代码:
string File = "../images/main/profile-icon.png";
if (Request.ContentLength != 0)
{
int Size = Request.Files[0].ContentLength / 1024;
if (Size <= 512)
{
string LocalFile = Request.Files[0].FileName;
int dot = LocalFile.LastIndexOf('.');
string FileType = LocalFile.Substring(dot + 1);
if (FileType == "gif" || FileType == "jpg" || FileType == "png" || FileType == "GIF" || FileType == "JPG" || FileType == "PNG")
{
int LastIndex = LocalFile.LastIndexOf(@"'") + 1;
File = LocalFile.Substring(LastIndex, LocalFile.Length - LastIndex);
File = DateTime.Today.ToString();
string Path = Server.MapPath(" ../images/profiles") + "..''" + File;
Request.Files[0].SaveAs(Path);
}
}
else
{
Response.Write("The file is too big !");
}
}
else
{
Response.Write("Unknown Error !");
}
问题是,在第三行代码中,我得到以下错误:
索引超出范围。必须非负且小于尺寸
这是表单HTML的来源:
<form name="Register" runat="server" style="margin-top: 15px;" onsubmit="return validateProfile('Register');">
<p>
photo:
<input type="file" name="File" style="margin-right:10px;" />
</p>
</form>
我的问题是为什么以及如何解决这个问题?
希望得到帮助,谢谢!
看来Files
数组没有元素,也许你可以添加一个检查:
if(Request.Files.Count > 0)
{
// continue here ...
}
这可能意味着你没有正确上传文件,并且它在请求中丢失。
编辑:尝试在表单标记中设置enctype="multipart/form-data"
。所以它会变成这样:
<form name="Register" runat="server" style="margin-top: 15px;" onsubmit="return validateProfile('Register');" enctype="multipart/form-data">