如何使用HTML5 File API加密二进制文件并上传到服务器

时间:2014-09-02 15:47:06

标签: javascript html5 encryption filereader cryptojs

我需要使用HTML5 FileReader APICryptoJS加密并将文件上传到Apache / PHP服务器

我已成功完成以下任务

  • 使用FileReader API读取文件
  • 使用readAsDataURL()函数
  • 将文件转换为base64
  • 使用以下

    加密

    CryptoJS.AES.encrypt(e.target.result,password);

但我无法将其作为File对象发送到服务器,因为我已经将其转换为文本对象,我无法将其转换回文件。以下是我的javascript文件和服务器端代码段。

<小时/> app.js

 var reader = new FileReader();

 // Read file callback!
 reader.onload = function (e) {

     // Use the CryptoJS library and the AES cypher to encrypt the 
     // contents of the file, held in e.target.result, with the password

     var encrypted = CryptoJS.AES.encrypt(e.target.result, password);


     //SEND FORM DATA
     var data = new FormData($("#fileinfo")[0]);

    /*The following line doesn't work because I'm not adding a File object, 
    * I'm adding file already converted to Base64 format
    */
     data.append('file-0','data:application/octet-stream,' + encrypted);

     $.ajax({
         url: 'upload.php',
         data: data,
         cache: false,
         contentType: false,
         processData: false,
         type: 'POST',
         success: function (data) {
             //alert(data);
         }
     });

 };

<小时/> upload.php的

<?php
var_dump($_FILES); //prints empty array
var_dump($_POST); //prints file as string 
?>

1 个答案:

答案 0 :(得分:4)

我在w3上找到了新草案的答案 如果有人需要,这是一个有效的代码

var reader = new FileReader();

// Read file callback!
reader.onload = function (e) {

var encrypted = CryptoJS.AES.encrypt(e.target.result, password);

var data = new FormData($("#fileinfo")[0]);

var encryptedFile = new File([encrypted], file.name + '.encrypted', {type: "text/plain", lastModified: new Date()});

data.append('file[0]', encryptedFile);

$.ajax({
     url: 'upload.php',
     data: data,
     cache: false,
     contentType: false,
     processData: false,
     type: 'POST',
     success: function (data) {
         //alert(data);
     }
 });

};

reader.readAsDataURL(file);
相关问题