从base64检查文件类型? [英] Checking file type from base64?
问题描述
我有一个带有以下OperationContract的WCF REST服务,可将文件保存在磁盘上:
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);
[OperationContract]
[WebInvoke(UriTemplate = "FileSave", Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
ResponseHandler FileSave(string fileName, string fileContent);
通过javascript发送文件-使用HTML File API =>二进制数据=> base-64编码的ASCII字符串(= fileContent在操作合同中已收到)
Files are sent through javascript - using HTML File API => binary data => base-64 encoded ASCII string (=fileContent is recieved in the operation contract)
我想在将文件保存到磁盘之前检查文件类型. 我知道以下解决方案: https://codereview.stackexchange.com/questions/29301/checking- mime-type-from-a-base64-string 但我不确定这是否是最好的方法.另外,我测试了上传多个txt文件,每个文件都有不同的前5个字符.
I want to check the file type before saving the file on the disk. I am aware of the following solution: https://codereview.stackexchange.com/questions/29301/checking-mime-type-from-a-base64-string 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.
因此,我正在寻找一个代码片段,其中应包括检查几种常见的文件类型.
So I am looking for a code snippet that would include checking for several common file types.
谢谢您的任何想法
推荐答案
在此处检查此链接:
http://codeanalyse.com/2016/10/02/extracting-file-extension-base64-string/
这将包括检查几种常见的文件类型"
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屋!