gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 08:18:03 24 4
gpt4 key购买 nike

我需要用 HTML5 FileReader API 加密文件并将其上传到 Apache/PHP 服务器和 CryptoJS

我已成功完成以下操作

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

    CryptoJS.AES.encrypt(e.target.result, 密码);

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


应用程序.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);
}
});

};


上传.php

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

最佳答案

我在 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);

关于javascript - 如何使用 HTML5 文件 API 加密二进制文件并上传到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25627399/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com