javascript 使用 html5 通过 ajax 和 jquery 上传文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14455529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using html5 for file upload with ajax and jquery
提问by de-bugged
So i am trying to upload an image along with form data to server. I'm using FileReader API to convert image to data and upload to server. I'm following the code similar to HTML5 uploader using AJAX Jquery.
所以我试图将图像与表单数据一起上传到服务器。我正在使用 FileReader API 将图像转换为数据并上传到服务器。我正在使用 AJAX Jquery跟踪类似于HTML5 上传器的代码。
The data is converted in jquery, but nothing is being sent to server and there is no error generated.
数据在 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 Code
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);
?>
Is the problem due to large image file or FileReader API?
问题是由于大图像文件还是 FileReader API?
回答by Deep Frozen
I'm not sure if file upload works with filereaders, but there is a different way to make it work:
我不确定文件上传是否适用于文件阅读器,但有一种不同的方法可以使其工作:
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);
}
}
This way you send the data to the PHP file and you can use $_FILES
to process it. Unfortunately, this does not work in IE as far as I know. There might be plugins available that make this possible in IE, but I don't know any of them.
通过这种方式,您可以将数据发送到 PHP 文件,然后您可以使用$_FILES
它来处理它。不幸的是,据我所知,这在 IE 中不起作用。可能有可用的插件可以在 IE 中实现这一点,但我不知道其中任何一个。