使用html5使用ajax和jquery上传文件

所以我试图将图像与表单数据一起上传到服务器。 我正在使用FileReader API将图像转换为数据并上传到服务器。 我使用AJAX Jquery跟踪类似于HTML5上传器的代码。

数据在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代码

  $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中实现这一点,但我不知道它们中的任何一个。