在我的网络应用程序(asp.net,c#)中,我在页面中上传视频文件,但我只想上传 flv 视频。上传其他扩展视频时如何限制?
12 回答
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")
在服务器上,您可以检查 MIME 类型,在此处或在 google 上查找 flv mime 类型。
您应该检查 mime 类型是否为
video/x-flv
例如,如果您在 C# 中使用 FileUpload,您可以这样做
FileUpload.PostedFile.ContentType == "video/x-flv"
string FileExtn = System.IO.Path.GetExtension(fpdDocument.PostedFile.FileName);
上述方法适用于 Firefox 和 IE:我可以查看所有类型的文件,如 zip、txt、xls、xlsx、doc、docx、jpg、png。
但是当我尝试从谷歌浏览器中找到文件的扩展名时,我失败了。
我不确定这是否是您想要的,但是:
Directory.GetFiles(@"c:\mydir", "*.flv");
或者:
Path.GetExtension(@"c:\test.flv")
此外,如果您有FileInfo fi
,您可以简单地执行以下操作:
string ext = fi.Extension;
并且它将保存文件的扩展名(注意:它将包括.
,因此上述结果可能是:.jpg
.txt
,依此类推....
值得一提的是如何在获取扩展的同时删除扩展:
var name = Path.GetFileNameWithoutExtension(fileFullName); // Get the name only
var extension = Path.GetExtension(fileFullName); // Get the extension only
在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);
}
您将无法限制用户在客户端上传的文件类型[*]。您只能在服务器端执行此操作。如果用户上传了不正确的文件,您只有在上传文件后才能识别出来。没有可靠和安全的方法来阻止用户上传他们想要的任何文件格式。
[*] 是的,你可以在开始上传之前做各种聪明的事情来检测文件扩展名,但不要依赖它。有人会绕过它,迟早会上传他们喜欢的任何东西。
private string GetExtension(string attachment_name)
{
var index_point = attachment_name.IndexOf(".") + 1;
return attachment_name.Substring(index_point);
}
此解决方案还有助于处理多个扩展,例如“Avishay.student.DB”
FileInfo FileInf = new FileInfo(filePath);
string strExtention = FileInf.Name.Replace(System.IO.Path.GetFileNameWithoutExtension(FileInf.Name), "");