在进行文件上传时,OSS 服务根据请求头中的 Content-MD5 值来校验上传到 OSS 的文件与获取文件上传链接时指定的本地文件是否一致。当 OSS 服务接收文件时,将其所计算的文件Content-MD5值和请求头中的 Content-MD5 进行比对,两者一致时才可以上传成功,从而保证上传文件的一致性。
文件Content-MD5计算说明
文件的 Content-MD5 值的计算步骤说明如下:
(1)先对文件的二进制Byte数组进行计算获得MD5加密后的二进制Byte数组(128位)。
(2)再对这个MD5加密后所获得的二进制Byte数组进行Base64编码(注意不是对MD5的32位字符进行编码)。
文件Content-MD5计算代码示例
JAVA代码示例
public static void main(String[] args) {
String filePath = "D:/测试文件.pdf";
// 对文件二进制字节流计算ContentMD5
String fileContentMD5 = getFileContentMD5(filePath);
System.out.println("文件Content-MD5值:" + fileContentMD5);
}
/***
* 计算文件的Content-MD5
* @param filePath 文件路径
* @return
*/
public static String getFileContentMD5(String filePath) {
// 获取文件MD5的二进制数组(128位)
byte[] bytes = getFileMD5Bytes128(filePath);
// 对文件MD5的二进制数组进行base64编码
return new String(Base64.encodeBase64(bytes));
}
/***
* 获取文件MD5-二进制数组(128位)
*
* @param filePath
* @return
* @throws IOException
*/
public static byte[] getFileMD5Bytes128(String filePath) {
FileInputStream fis = null;
byte[] md5Bytes = null;
try {
File file = new File(filePath);
fis = new FileInputStream(file);
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int length = -1;
while ((length = fis.read(buffer, 0, 1024)) != -1) {
md5.update(buffer, 0, length);
}
md5Bytes = md5.digest();
fis.close();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return md5Bytes;
}
PHP代码示例
$filePath = "D:/测试文件.pdf";
// 文件Content-MD5值
$fileContentMD5 = getFileContentMD5($filePath);
echo("文件Content-MD5值:".$fileContentMD5);
function getFileContentMD5($filePath){
//获取文件MD5的128位二进制数组
$md5Bytes = md5_file($filePath,true);
//计算文件的Content-MD5
$contentMD5 = base64_encode($md5Bytes);
return $contentMD5;
}
.NET代码示例
public static void Main(string[] args)
{
string filePath = "D:/测试文件.pdf";
string fileContentMD5 = GetFileContentMD5(filePath);
MessageBox.Show("文件Content-MD5值:" + fileContentMD5);
}
public static string GetFileContentMD5(string filePath)
{
string contentMD5 = null;
try
{
FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);
System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
// 先计算出上传内容的MD5,其值是一个128位(128 bit)的二进制数组
byte[] md5Bytes = md5.ComputeHash(file);
file.Close();
// 再对这个二进制数组进行base64编码
contentMD5 = Convert.ToBase64String(md5Bytes).ToString();
return contentMD5;
}
catch (Exception ex)
{
MessageBox.Show("错误信息", "计算文件的Content-MD5值时发生异常:" + ex.Message);
return contentMD5;
}
}