獲取文件MD5值(JS、JAVA)


文章HTML代碼翻譯於地址:https://www.cnblogs.com/linyihai/p/7040786.html

文件MD5有啥用?

  文件上傳時會上傳文件的信息此時將文件的md5上傳,服務器中存儲這個md5值,並存儲這個md5值所對應的已上傳字節長度,比如未上傳對應為0,已上傳對應為-1,已上傳200字節就對應200,這個上傳的時候可以匹配到這個文件在服務器中的狀態,方便做斷點續傳,只要源文件沒有更改,即使換個名字,換個賬戶都可以在服務器找到對應的文件,所以當服務器中有已經上傳完畢的此文件時,別人再上傳這個文件就可以實現秒傳。

  下面代碼實現HTML選擇文件獲取MD5值、JAVA根據文件地址獲取文件MD5值。

 

<!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>
    <!-- https://github.com/satazor/js-spark-md5 -->
    <script src="spark-md5.min.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>

 

/**
     * 獲取文件的md5
     * @param filePath 文件地址
     * @param fileName 文件名
     * @return
     */
    public static String getFileMd5Value(String filePath, String fileName){
        File file = new File(filePath + File.separator + fileName);
        if(!file.exists() || !file.isFile()){
            return "";
        }
        byte[] buffer = new byte[2048];
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            FileInputStream in = new FileInputStream(file);
            while(true){
                int len = in.read(buffer,0,2048);
                if(len != -1){
                    digest.update(buffer, 0, len);
                }else{
                    break;
                }
            }
            in.close();
             
            byte[] md5Bytes  = digest.digest();
            StringBuffer hexValue = new StringBuffer();
            for (int i = 0; i < md5Bytes.length; i++) {
                int val = ((int) md5Bytes[i]) & 0xff;
                if (val < 16) {
                    hexValue.append("0");
                }
                hexValue.append(Integer.toHexString(val));
            }
            return hexValue.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    
    public static void main(String[] args) {
        System.out.println(Snippet.getFileMd5Value("C:\\Users\\Administrator\\Desktop", "test.txt"));
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM