从 base64 检查文件类型? [英] Checking file type from base64?
问题描述
我有一个 WCF REST 服务,其中包含以下 OperationContract 可将文件保存在磁盘上:
I have a WCF REST Service with the following OperationContract that saves files on the disk:
[OperationContract]
[WebInvoke(UriTemplate = "FileSave", Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
ResponseHandler FileSave(string fileName, string fileContent);
文件通过 javascript 发送 - 使用 HTML 文件 API =>二进制数据 =>base-64 编码的 ASCII 字符串(=操作合约中收到的文件内容)
Files are sent through javascript - using HTML File API => binary data => base-64 encoded ASCII string (=fileContent is recieved in the operation contract)
我想在将文件保存到磁盘之前检查文件类型.我知道 从 base64 字符串检查 MIME 类型Code Review Stack Exchange,但我不确定这是否是最好的方法.另外,我测试了上传几个 .txt 文件,每个文件的前 5 个字符都不同.
I want to check the file type before saving the file on the disk. I am aware of Checking MIME Type from a base64 string on the Code Review Stack Exchange but I am not sure if it is the best way to go. Also, I have tested uploading several .txt files and each one has different first 5 chars.
我正在寻找包含检查几种常见文件类型的代码片段.
I am looking for a code snippet that would include checking for several common file types.
推荐答案
在此处查看此链接:
这将包括检查几种常见的文件类型"
This "would include checking for several common file types"
/// <summary>
/// To demonstrate extraction of file extension from base64 string.
/// </summary>
/// <param name="base64String">base64 string.</param>
/// <returns>Henceforth file extension from string.</returns>
public static string GetFileExtension(string base64String)
{
var data = base64String.Substring(0, 5);
switch (data.ToUpper())
{
case "IVBOR":
return "png";
case "/9J/4":
return "jpg";
case "AAAAF":
return "mp4";
case "JVBER":
return "pdf";
case "AAABA":
return "ico";
case "UMFYI":
return "rar";
case "E1XYD":
return "rtf";
case "U1PKC":
return "txt";
case "MQOWM":
case "77U/M":
return "srt";
default:
return string.Empty;
}
}
这篇关于从 base64 检查文件类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!