自动 - 下载加密文件

时间:2016-11-08 03:21:00

标签: javascript jquery encryption filereader cryptojs

我正在尝试加密,然后从客户端的文件夹下载文件。我有以下代码,但实际的加密文件没有下载。构建下载URL是我遇到问题的地方。

<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Get Directory</title>
<!-- Update your jQuery version??? -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="assets/js/aes.js"></script>
<script> // type="text/javascript" is unnecessary in html5

// Short version of doing `$(document).ready(function(){`
// and safer naming conflicts with $
jQuery(function($) { 

    $('#file-input').on('change', function() {

        // You can't use the same reader for all the files
         var array1 = new Array

        $.each(this.files, function(i, file) {

            // Uses different reader for all files
            var reader = new FileReader
            var downloadUrl = ''
            reader.onload = function() {
                // reader.result refer to dataUrl
                // theFile is the blob... CryptoJS wants a string...
                var encrypted = CryptoJS.AES.encrypt(reader.result, '12334')
                downloadUrl = 'data:application/octet-stream,' + encrypted;
                array1.push(downloadUrl);
                setTimeout("window.location.assign('" + downloadUrl + file.name + '.encrypted'+ "');", 500)
            }

            reader.readAsDataURL(file)
            $('#thelist').append('FILES: ' + file.name + '<br>')

        })

    })
})
</script>
</head>
<body>
<input type="file" id="file-input" webkitdirectory="" directory="">
<div id="thelist"></div>
 </body>
</html>

1 个答案:

答案 0 :(得分:0)

如果有人正在寻找这个,我能够解决它如下。

              var reader = new FileReader();
                reader.onload = function (e) {
                var encrypted = CryptoJS.AES.encrypt(reader.result, '12345');
                var dataUrl = 'data:data:application/octet-stream,' + encrypted;
                array1.push('href=data:data:application/octet-stream,' + encrypted);

                var link = document.createElement("a");
                link.download = file.name + '.encrypted';
                link.target = "_blank";

                // Construct the uri
                link.href = dataUrl;
                document.body.appendChild(link);
                link.click();

                // Cleanup the DOM
                document.body.removeChild(link);
                delete link;
                };
                $('#thelist').append('FILES: ' + file.name + '<br>')
                reader.readAsDataURL(file);
              })