简体   繁体   English

使用html5进行文件上传,使用ajax和jquery

[英]using html5 for file upload with ajax and jquery

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. 我正在使用FileReader API将图像转换为数据并上传到服务器。 I'm following the code similar to HTML5 uploader using AJAX Jquery . 使用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?

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. 这样您就可以将数据发送到PHP文件,并且可以使用$_FILES来处理它。 Unfortunately, this does not work in IE as far as I know. 不幸的是,据我所知,这在IE中不起作用。 There might be plugins available that make this possible in IE, but I don't know any of them. 可能有可用的插件可以在IE中实现这一点,但我不知道它们中的任何一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM