ASP.Net, c#, iis, mime类型,文件上传条件
本文关键字:文件 类型 条件 mime Net iis ASP | 更新日期: 2023-09-27 18:08:16
我在网站上有一个文件上传web-form,它只需要接受某些格式(或MIME类型)…
下面的代码是完美的工作,除了,它不上传。docx文件到服务器!这是唯一不工作的文件类型…我仔细检查了每一行代码,甚至进入IIS管理器以确保.DOCX MIME类型被继承,并且它们是…
有没有人知道为什么。docx文件不会像其他文件类型一样上传到服务器?
代码片段:
string savePath = "D:''HIDDEN PATH HERE";
string fileMsg;
// Before attempting to perform operations
// on the file, verify that the FileUpload
// control contains a file.
if (FileUpload1.HasFile)
{
// Check to see that the content type is proper and allowed.
// DOC: application/doc, appl/text, application/vnd.msword, application/vnd.ms-word, application/winword, application/word, application/x-msw6, application/x-msword
if (
FileUpload1.PostedFile.ContentType == "text/rtf" ||
FileUpload1.PostedFile.ContentType == "application/doc" ||
FileUpload1.PostedFile.ContentType == "appl/text" ||
FileUpload1.PostedFile.ContentType == "application/vnd.msword" ||
FileUpload1.PostedFile.ContentType == "application/vnd.ms-word" ||
FileUpload1.PostedFile.ContentType == "application/winword" ||
FileUpload1.PostedFile.ContentType == "application/word" ||
FileUpload1.PostedFile.ContentType == "application/msword" ||
FileUpload1.PostedFile.ContentType == "application/x-msw6" ||
FileUpload1.PostedFile.ContentType == "application/x-msword" ||
FileUpload1.PostedFile.ContentType == "application/pdf" ||
FileUpload1.PostedFile.ContentType == "application/x-pdf" ||
FileUpload1.PostedFile.ContentType == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
FileUpload1.PostedFile.ContentType == "application/vnd.openxmlformats-officedocument.wordprocessingml.template"
)
{
// Get the name of the file to upload.
String fileName = FileUpload1.FileName;
// Append the name of the file to upload to the path.
savePath += strnow + fileName;
// Call the SaveAs method to save the
// uploaded file to the specified path.
// This example does not perform all
// the necessary error checking.
// If a file with the same name
// already exists in the specified path,
// the uploaded file overwrites it.
FileUpload1.SaveAs(savePath);
// Notify the user of the name of the file
// was saved under.
//fileMsg = "Your file was saved as " + fileName;
fileMsg = "";
}
else
{
fileMsg = "Your file was not an accepted format. Please use PDF, RTF or DOC formats.";
}
看这个答案,它指向这个页面。
DOCX Mime Type:application/vnd.openxmlformats-officedocument.wordprocessingml.document
编辑:抱歉,我没在单子上看到。如果你想允许DOCX,为什么不直接检查"。DOCX"作为扩展名。
|| FileUpload1.PostedFile.FileName.ToLower().Substring(FileUpload1.PostedFile.FileName.Length - 4) == "docx"
您应该阅读扩展,而不是检查mime类型。MIME类型由浏览器设置,在不同的计算机之间可能会有所不同。这不是他们的目的。
同样,不管你来自什么背景,如果你有一个这样的if声明,你至少应该感到一点点羞耻。
string[] acceptedExtensions = new string[] { ".docx", ".doc", ".txt", ".etc" };
// snip
if(acceptedExtensions.Contains(Path.GetExtension(FileUpload1.PostedFile.Filename)))
{
AcceptFile(FileUpload1.PostedFile);
}