【发布时间】:2017-12-04 16:43:19
【问题描述】:
我正在尝试使用 js 文件阅读器和 AJAX 将文件上传到我的服务器。
我使用FileAPI 和fileReader 读取文件并将其转换为字符串,然后通过AJAX 请求将其发送到服务器。 这是我的客户端 js 代码:
function upload() {
var file = document.getElementById('periodExcel').files[0];
if (file) {
console.log(file);
var reader = new FileReader();
reader.readAsText(file, file.type);
console.log(reader);
reader.onload = uploadAndRun;
}
}
function uploadAndRun(event) {
console.log(event);
var result = event.target.result;
$('#js').html(result);
var fileName = document.getElementById('periodExcel').files[0].name; //Should be 'picture.jpg'
$.post('./upload.php', {data: result, name: fileName}, function(result2){
$('#php').html(result2);
});
}
这里是上传的php脚本:
file_put_contents('upload/' . $_POST['name'], $_POST['data']);
它只是使用 php file_put_contents 函数写入文件。
我的问题是上传的文件已损坏并且与原始文件的大小不同(它更大)。
我尝试使用 php file_get_contents 函数读取相同的文件并使用 file_put_contents 再次写入,结果文件很好,与原始文件相同。
然后我尝试比较两个字符串(来自 file reader 的字符串和来自 file_get_contents 的字符串)并使用 @987654329 比较两个字符串@,这让我知道来自fileReader 的字符串大于来自file_get_contents 的字符串。
那么,我的代码有什么问题,以及在使用readAsText 函数时如何使用 FileReader 以这种方式上传文件。
【问题讨论】:
-
上传文件时应使用
FormDataapi确保enctype设置正确 -
我尝试使用它但它没有被填充(追加不起作用),并且发生阻止提交的错误。
标签: javascript php filereader fileapi