2014-09-02 71 views
3

我需要加密和上傳文件到Apache/PHP服務器HTML5 FileReader APICryptoJS如何加密與HTML5文件API的二進制文件,並上傳到服務器

我成功地完成以下

  • 閱讀文件的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 
?> 
+0

這功能已經由我實現...上傳它時,你可以刪除'data:application/octet - 流的原因,你不能解密它 – 2014-09-02 16:03:01

+0

謝謝@ArpitSrivastava我解決了這個問題。 – 2014-09-02 16:04:02

回答

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); 
+0

你有沒有進一步與此? – niieani 2015-10-14 12:50:25

+0

@niieani,我沒有。此代碼至少在Chrome中運行正常。 – 2015-10-15 10:14:46

+0

這是錯的...它應該是: var encrypted = CryptoJS.AES.encrypt(e.target.result.split(「,」)[1],password); – Zibri 2015-10-22 23:47:35

相關問題