在我的Web应用程序(asp.net,c#)中,我正在页面中上传视频文件,但我只想上传flv视频。上传其他扩展视频时如何限制?
在我的Web应用程序(asp.net,c#)中,我正在页面中上传视频文件,但我只想上传flv视频。上传其他扩展视频时如何限制?
Answers:
string myFilePath = @"C:\MyFile.txt";
string ext = Path.GetExtension(myFilePath);
// ext would be ".txt"
您可以简单地读取文件流
using (var target = new MemoryStream())
{
postedFile.InputStream.CopyTo(target);
var array = target.ToArray();
}
前5/6个索引将告诉您文件类型。在FLV其的情况下70,76,86,1,5。
private static readonly byte[] FLV = { 70, 76, 86, 1, 5};
bool isAllowed = array.Take(5).SequenceEqual(FLV);
如果isAllowed等于,true则其FLV。
要么
读取文件内容
var contentArray = target.GetBuffer();
var content = Encoding.ASCII.GetString(contentArray);
前两个/三个字母将告诉您文件类型。
如果是FLV,则其“ FLV ......”
content.StartsWith("FLV")
您将无法限制用户在客户端[*]上载的文件类型。您将只能在服务器端执行此操作。如果用户上传了不正确的文件,则只有在文件上传后,您才能识别出该文件。没有可靠且安全的方法来阻止用户上传所需的任何文件格式。
[*]是的,您可以在开始上传之前做各种聪明的事情来检测文件扩展名,但不要依赖它。有人会绕过它,早晚上传任何他们喜欢的东西。
在DotNetPerls上找到了我更喜欢的替代解决方案,因为它不需要您指定路径。这是一个在自定义方法的帮助下填充数组的示例
// This custom method takes a path
// and adds all files and folder names to the 'files' array
string[] files = Utilities.FileList("C:\", "");
// Then for each array item...
foreach (string f in files)
{
// Here is the important line I used to ommit .DLL files:
if (!f.EndsWith(".dll", StringComparison.Ordinal))
// then populated a listBox with the array contents
myListBox.Items.Add(f);
}
string FileExtn = System.IO.Path.GetExtension(fpdDocument.PostedFile.FileName);
上面的方法在Firefox和IE上都可以正常工作,我能够查看所有类型的文件,例如zip,txt,xls,xlsx,doc,docx,jpg,png
但是当我尝试从googlechrome查找文件扩展名时,我失败了。