解决spark-md5.js和java计算文件md5值不一致问题

时间:2022-09-22 18:52:14

正确代码如下

java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Test {

    public static void main(String[] args) {
        try {
            File file = new File("H://QQ图片20171127002343.gif");
            FileInputStream fis = new FileInputStream(file);
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[1024];
            int length = -1;
            while ((length = fis.read(buffer, 0, 1024)) != -1) {
                md.update(buffer, 0, length);
            }
            BigInteger bigInt = new BigInteger(1, md.digest());
            System.out.println("文件md5值:" + bigInt.toString(16));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
html

<html>    
<head>    
<script type="text/javascript" src="spark-md5.js" ></script>    
<script src="https://cdn.bootcss.com/spark-md5/3.0.0/spark-md5.js"></script>
</head>    
    
<body>    
<input type="file" id="file" />    
<div id="box"></div>    
<button id="cal" type="button" onclick="calculate()">计算md5</button>    
</body>    
    
<script>    
    
function calculate(){    
    var fileReader = new FileReader(),    
        box=document.getElementById('box');    
        blobSlice = File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice,    
        file = document.getElementById("file").files[0],    
        chunkSize = 2097152,    
        // read in chunks of 2MB    
        chunks = Math.ceil(file.size / chunkSize),    
        currentChunk = 0,    
        spark = new SparkMD5();    
    
    fileReader.onload = function(e) {    
        console.log("read chunk nr", currentChunk + 1, "of", chunks);    
        spark.appendBinary(e.target.result); // append binary string    
        currentChunk++;    
    
        if (currentChunk < chunks) {    
            loadNext();    
        }    
        else {    
            console.log("finished loading");    
            box.innerText='MD5 hash:'+spark.end();    
            console.info("computed hash", spark.end()); // compute hash    
        }    
    };    
    
    function loadNext() {    
        var start = currentChunk * chunkSize,    
            end = start + chunkSize >= file.size ? file.size : start + chunkSize;    
    
        fileReader.readAsBinaryString(blobSlice.call(file, start, end));    
    };    
    
    loadNext();    
}    
    
</script>    
</html>
没时间研究原理,之前应该是编码方式问题,html头部设置成UTF-8没效果,弃疗...换了网上新找的的代码ok

错误代码如下

<!DOCTYPE html>
<html>
  <head>
      <meta charset="utf-8">
  </head> 
  <body>
         <form id="fileupload" action="" method="POST" enctype="multipart/form-data">
            <div>
                <div>                                                             
                    添加文件
                    <input type="file" name="" id="fileinput">                                                                     
                </div>

                <progress class='progressbar' value="0" max="100" style='width:500px;margin-top:20px'></progress>
                <div style='margin-top:20px'>
                    <span id="handler_info" ></span>
                </div>
            </div>   
        </form>
    <script src="./spark-md5.js" type="text/javascript"></script>
    <script>
        function get_filemd5sum(ofile) {
            var file = ofile;
            var tmp_md5;
            var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
                // file = this.files[0],
                chunkSize = 8097152, // Read in chunks of 2MB
                chunks = Math.ceil(file.size / chunkSize),
                currentChunk = 0,
                spark = new SparkMD5.ArrayBuffer(),
                fileReader = new FileReader();

            fileReader.onload = function(e) {
                // console.log('read chunk nr', currentChunk + 1, 'of', chunks);
                spark.append(e.target.result); // Append array buffer
                currentChunk++;
                var md5_progress = Math.floor((currentChunk / chunks) * 100);

                console.log(file.name + "  正在处理,请稍等," + "已完成" + md5_progress + "%");
                var handler_info = document.getElementById("handler_info");
                var progressbar = document.getElementsByClassName("progressbar")[0];
                handler_info.innerHTML=file.name + "  正在处理,请稍等," + "已完成" + md5_progress + "%"
                progressbar.value =md5_progress;
                if (currentChunk < chunks) {
                    loadNext();
                } else {
                    tmp_md5 = spark.end();
                    console.log(tmp_md5)
                    handler_info.innerHTML = file.name + "的MD5值是:" + tmp_md5;
                }
            };

            fileReader.onerror = function() {
                console.warn('oops, something went wrong.');
            };

            function loadNext() {
                var start = currentChunk * chunkSize,
                    end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
                fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
            }
            loadNext();
        }

        var uploadfile  = document.getElementById('fileinput')
        uploadfile.onchange = function(e){
            var file = this.files[0];
             if(!file) {
                alert('请选择文件!');
                return false;
            }
            get_filemd5sum(file)
        }
    </script>
   </body> 
</html>

错误代码来源:传送门

其实也没错,就是编码方式可能有问题,研究半天不知道改哪里


spark-md5.js CDN地址:又拍云

参(chao)考(xi)文章:JS JAVA MD5 计算