使用HTML5、Ajax和jQuery实现文件上传

4

我正在尝试将图像和表单数据一起上传到服务器。我使用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引起的?

1个回答

12

我不确定文件上传是否可以使用filereaders,但有另一种方法可以让它工作:

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 中成为可能,但我不知道任何一个。


嗨Rune,我尝试了你的方法。formData的内容是append:function append(),没有其他表单数据。我也尝试将所有表单数据附加到formData中并发出post请求,但没有向服务器发送任何数据。有什么建议吗? - de-bugged
以及 PHP 端的未定义内容。 - de-bugged
@de-bugged 我没有看到任何可能导致失败的东西... 你是否收到了成功的回调,或者它在某个地方出错了?你的 PHP 脚本可能会有错误导致它失败。 - Deep Frozen
1
你应该得到一亿的加分!我一整天都在寻找一个跨域解决方案,而你的是唯一有效的。谢谢! - Whatevo
使用 contentType: "application/octet-stream" 可以帮助处理一些服务器的问题。 - Christophe Roussy
显示剩余7条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接