簡體   English   中英

使用html5進行文件上傳,使用ajax和jquery

[英]using html5 for file upload with ajax and 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代碼

<?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中實現這一點,但我不知道它們中的任何一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM