检查是否是gzip压缩的base64图像

时间:2016-10-04 16:54:51

标签: javascript apache http base64 mod-deflate

我正在开发一个网络应用程序,流程是这样的:浏览器从服务器获取图像作为base64数据,然后JavaScript编码这些图像等(作为Web服务器,我们使用apache与mod_deflate'模块我想检查是否有压缩(gzip)图像的那些。

嗯,问题是base64图像没有HTTP头,所以我该如何检查呢?任何的想法?感谢。

2 个答案:

答案 0 :(得分:1)

如果您从服务器请求图像数据,响应将始终包含一些标题,如果内容被压缩(gzip),您将看到标题content-encoding: gzip

但是,如果您想知道实际(base64编码)数据是否被压缩(gzip),您将解码base64字符串的前4个字符,以获得至少前2个字节。如果前两个字节是1F 8B,则表示您正在处理gzip压缩数据。

如果前2个字节是50 4B它的压缩数据。 如果前3个字节是FF D8 FF它的jpg / jpeg数据。 如果前4个字节是89 50 4E 47它的png数据。

请参阅:few ways

答案 1 :(得分:1)

您正在以base64格式从服务器获取图像,因此现在解码为base64格式的图像并将输出存储在变量中。现在让我们看一下解码后的字符串并检查已解码字符串的起始10-12个字符,因为文件扩展名存储在文件的开头。

例如,如果您想了解上述逻辑,请在记事本中打开jpeg / png图像并观察文件中的前10-12个字符,然后您可以在该文件中找到各自的文件扩展名

所以我也在这里做同样的事情我将在解码文件中搜索GZIP字符串,如果找到它然后文件是GZIP格式,否则它不是。它可能有点令人困惑。让我告诉你这个代码: `

var encodedData; //This one was fetched from the server
var decodedData = atob(encodedData); //atob() decodes the string which is in base64 format
var extension = "GZIP"
var IndexOfGZIP = decodedData.IndexOf(extension) //Checking for GZIP word in decoded data

//If it is equal to -1 it says that GZIP is not found in data
if( IndexOfGZIP !== -1 ){ 

    //Normally the file extensions are found in the starting of the file only and hence I'm taking only first 11 characters into consideration.
    if( IndexOfGZIP >= 0 && IndexOfGZIP <=10 ){
        console.log("This is a GZIP file only")
    }else{
        console.log("File is not in GZIP Format")
    }
}else{
    console.log("File is not in GZIP Format")
}

` 希望这会对你有所帮助。