FileHeaderEncode验证后保存文件时出现问题 [英] Problem in Saving the File after FileHeaderEncode Verification
问题描述
我在FileHeaderEncode验证后保存文件时遇到问题.
我只是想验证上传的文档实际上是jpeg图像,而不仅仅是说一个重命名为.jpeg扩展名的文本文件.
为了验证这一点,我使用了一种称为"DetectFileheaderEncode"的方法.但是,每当我使用此方法并尝试保存图像时,它会将图像保存为0大小,因此,该图像不可用?
请你帮助我好吗?
谢谢
乖dd
代码如下:
Hi, I''m having a problem saving a file after FileHeaderEncode verification.
I am just trying to verify that the uploaded document is actually a jpeg image, not just say, a Text file renamed to have a .jpeg extension.
To verify this I use method which I called "DetectFileheaderEncode". But whenever I use this method and try to save the image, it saves the image as 0 size therefore, the image is not available?
Could you please help me?
Thank you,
codddy
The code is as below:
protected void btnUpload_Click(object sender, EventArgs e)
{
String savePath = @"C:\\Users\\xx\\Desktop\\fileupload\\";
try
{
if (FileUpload1.HasFile)
{
string fileName = Server.HtmlEncode(FileUpload1.FileName);
Boolean verified = VerifyUploadJpegImage(FileUpload1);
if (verified)
{
// Append the name of the file to upload to the path.
savePath += fileName;
FileUpload1.SaveAs(savePath);
// Notify the user that their file was successfully uploaded.
lblUploadStatus.Text = "Your file was uploaded successfully.";
lblUploadStatus.ForeColor = Color.Green;
}
else
{
// Invalid upload file
// notify the user why their file was not uploaded.
lblUploadStatus.Text = "Your file was not uploaded because " +
"it is not a jpegImage";
lblUploadStatus.ForeColor = Color.Red;
}
}
else
{
lblUploadStatus.Text = "You have not specified a file.";
}
}
catch (Exception ex)
{
lblUploadStatus.Text = "ERROR:" + ex.Message;
}
}
private Boolean VerifyUploadJpegImage(FileUpload fileUpload)
{
Boolean verified = false;
String fileName = Server.HtmlEncode(fileUpload.FileName);
String extension = System.IO.Path.GetExtension(fileName);
String contentType = fileUpload.PostedFile.ContentType;
String fileheaderEncoding = DetectFileheaderEncode(fileUpload);
if (((extension == ".jpg") || (extension == ".jpeg")) && (contentType == "image/jpeg") && (fileheaderEncoding == "255216"))
{
verified = true;
}
return verified;
}
private String DetectFileheaderEncode(FileUpload fileUpload)
{
String encode = String.Empty;
System.IO.BinaryReader r = new System.IO.BinaryReader(fileUpload.PostedFile.InputStream);
string fileclass = "";
byte buffer;
try
{
buffer = r.ReadByte();
fileclass = buffer.ToString();
buffer = r.ReadByte();
fileclass += buffer.ToString();
}
catch(Exception ex)
{
}
r.Close();
encode = fileclass;
return encode;
}
推荐答案
好,我解决了这个问题. :)
我刚刚在DetectFileheaderEncode方法中注释了r.Close(),它现在可以正常工作.
Ok I solved the problem. :)
I just commented out r.Close() in DetectFileheaderEncode method, and it''s working correctly now.
这篇关于FileHeaderEncode验证后保存文件时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!