所以我正在尝试将图像连同表单数据一起上传到服务器。我正在使用 FileReader API 将图像转换为数据并上传到服务器。我遵循类似于 HTML5 uploader using AJAX Jquery 的代码.
数据在 jquery 中转换,但没有任何内容发送到服务器,也没有生成错误。
$('#formupload').on('submit', function(e){
e.preventDefault();
var hasError = false;
var file = document.getElementById('file').files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = shipOff;
function shipOff(event) {
result = new Image();
result.src = event.target.result;
var fileName = document.getElementById('file').files[0].name;
$.post('test.php', { data: result, name: fileName });
}
PHP代码
<?php
$data = $_POST['data'];
$fileName = $_POST['name'];
echo $fileName;
$fp = fopen('/uploads/'.$fileName,'w'); //Prepends timestamp to prevent overwriting
fwrite($fp, $data);
fclose($fp);
$returnData = array( "serverFile" => $fileName );
echo json_encode($returnData);
?>
问题是由大图像文件还是 FileReader API 引起的?
最佳答案
我不确定文件上传是否适用于文件读取器,但有一种不同的方法可以让它工作:
var formData = new FormData($(".file_upload_form")[0]);
$.ajax({
url: "upload_file.php", // server script to process data (POST !!!)
type: 'POST',
xhr: function() { // custom xhr
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // check if upload property exists
// for handling the progress of the upload
myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
}
return myXhr;
},
success: function(result) {
console.log($.ajaxSettings.xhr().upload);
alert(result);
},
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: "application/octet-stream", // Helps recognize data as bytes
processData: false
});
function progressHandlingFunction(e) {
if (e.lengthComputable) {
$("#progress").text(e.loaded + " / " + e.total);
}
}
这样您就可以将数据发送到 PHP 文件,您可以使用 $_FILES
来处理它。不幸的是,据我所知,这在 IE 中不起作用。可能有可用的插件可以在 IE 中实现这一点,但我不知道其中的任何一个。
关于javascript - 使用 html5 通过 ajax 和 jquery 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14455529/