1. 程式人生 > >解決spark-md5.js和java計算檔案md5值不一致問題

解決spark-md5.js和java計算檔案md5值不一致問題

正確程式碼如下

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地址:又拍雲