Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

c# - Checking file type from base64?

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);

Files are sent through javascript - using HTML File API => binary data => base-64 encoded ASCII string (=fileContent is recieved in the operation contract)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Check this link here:

https://web.archive.org/web/20170331115315/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;
 }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...