开发者

Saving different file formats

In my application I receive different files in base64string. After receiving those base64Strings my application needs to convert them into开发者_如何转开发 their original formats. These files could be pdf,txt,jpeg image,bmp image,gif image or png image formats. How do I know what format this file is in order to convert them to their respective formats. Is there any way the base64string gives this info. Any help will be appreciated.'


The base64 data only contains the file data itself, no metadata about it (including file name / extension). You could potentially try to parse the first few bytes of the decoded base64 data to try to find out the file type, but an easier approach would be for the service to add this information in some HTTP header (such as Content-Disposition).


I think you only need to convert it to binary format from base64string and save on disk. You only need to get the correct file extension or complete file name so that user can use associated program to open it.


The only reliable means to get the file type is through metadata associated with the file. If this is not available in your case, a workaround is to read the first few bytes of the file. Many common formats require that files of that format begin with a sequence of bytes, known as "magic numbers".

This Wikipedia article provides maic numbers for PDF, JPG, PNG, and GIF formats. BMP files typically begin with the constant 0x42 0x4D (*). Since text files contain only content, it would need to be a default option (i.e, if the first few bytes aren't recognized as a known magic number, assume it is a text file.)

The Base-64 encoding is simply the binary representation of the file. Converting back to a byte sequence and assessing the first few bytes should be sufficient to suggest a file is of a certain type. Note that this is an imperfect workaround; for instance, a text file that happens to start with a magic number (e.g., "BM") may be miscategorized as another type of file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜