![](/img/trans.png)
[英]How to validate an uploaded file a csv or not with out using content type property (with out checking the extension) of file upload control in c#?
[英]Validate uploaded file extension
上传文件效果很好,但是现在我正在尝试验证文件扩展名,并且FileUpload1
和FileUpload2
之间似乎有些干扰。
FileUpload1
用于上传.jpg或.png图像, FileUpload2
用于上传.pdf文件。
这是在BtnInsert_Click
事件上执行的代码:
protected void BtnInsert_Click(object sender, EventArgs e)
{
string[] validPhotoFile = { ".jpg", ".png" };
string validPDFFile = ".pdf";
string photoExt = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
string pdfExt = System.IO.Path.GetExtension(FileUpload2.PostedFile.FileName);
bool isValidPhotoFile = false;
bool isValidPDFFile = false;
for (int i = 0; i < validPhotoFile.Length; i++)
{
if (photoExt == "." + validPhotoFile[i])
{
isValidPhotoFile = true;
break;
}
}
for (int i = 0; i < validPDFFile.Length; i++)
{
if (pdfExt == "." + validPDFFile[i])
{
isValidPDFFile = true;
break;
}
}
if (!isValidPhotoFile)
{
PhotoErrorMessage.Text = "Upload .jpg or .png image!";
}
if (!isValidPDFFile)
{
PDFErrorMessage.Text = "Upload .pdf file!";
}
else
{
string photoFilPath = Path.GetFileName(FileUpload1.PostedFile.FileName.ToString());
string pdfFilPath = Path.GetFileName(FileUpload2.PostedFile.FileName.ToString());
string photoPath = Server.MapPath(@"~/PDFCover/" + fotoFilPath);
string pdfPath = Server.MapPath(@"~/PDF/" + pdfFilPath);
FileUpload1.PostedFile.SaveAs(photoPath);
FileUpload2.PostedFile.SaveAs(pdfPath);
SqlCommand cmd = new SqlCommand("INSERT INTO Book(Title,Content...) VALUES ('" + TextBox1.Text
+ "','" + TextBox2.Text + ... + "','" + "~/PDFCover/" + photoFilPath
+ "','" + "~/PDF/" + pdfFilPath + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
现在,即使我选择上传有效文件,它也会显示标签错误消息以上传有效文件。
bool CheckFileType(string fileName)
{
string ext = Path.GetExtension(fileName);
switch (ext.ToLower())
{
case ".gif":
return true;
case ".jpg":
return true;
case ".jpeg":
return true;
case ".png":
return true;
default:
return false;
}
}
if (CheckFileType(fuImage.FileName))
{
//..........
}
或使用RegularExpressionValidator:
<asp:RegularExpressionValidator
ID="regexValidateImageFil" runat="server" ControlToValidate="fuImage"
ErrorMessage="file type not allow."
ValidationExpression="^([0-9a-zA-Z_\-~ :\\])+(.jpg|.JPG|.jpeg|.JPEG|.bmp|.BMP|.gif|.GIF|.png|.PNG)$"></asp:RegularExpressionValidator>
您是同时上传两个文件还是一次上传一个文件? 如果一次仅一个,那么这些值之一将始终为false。
您还要在validPhotoFile和validPDFFile前面添加一个句点,像这样更改代码。
for (int i = 0; i < validPhotoFile.Length; i++)
{
if (photoExt == validPhotoFile[i]) // remove the period here it is already in your variables above
{
isValidPhotoFile = true;
break;
}
}
for (int i = 0; i < validPDFFile.Length; i++)
{
if (pdfExt == validPDFFile[i]) // remove the period here it is already in your variables above
{
isValidPDFFile = true;
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.