使用ajax和php上传文件

时间:2012-08-02 11:19:30

标签: php javascript ajax html5

我想使用ajax和php实现文件上传。我有一个表单输入标记。我想要输入标签的onchange事件,文件将被上传到服务器,我将在javascript中的变量中获取文件的路径!所以,我想保持在同一页面上传文件,获取javascript变量中的文件路径。

非常感谢任何伪代码,示例或教程。

3 个答案:

答案 0 :(得分:5)

演示网址: -

http://jquery.malsup.com/form/progress.html

您可以从此网址下载jQuery文件,并添加html <head>代码

http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js

http://malsup.github.com/jquery.form.js

试试这个:

这是我的html标记:

<!doctype html>
<head>
<title>File Upload Progress Demo #1</title>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }

.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
    <h1>File Upload Progress Demo #1</h1>
    <code>&lt;input type="file" name="myfile"></code>
        <form action="upload.php" method="post" enctype="multipart/form-data">
        <input type="file" name="uploadedfile"><br>
        <input type="submit" value="Upload File to Server">
    </form>

    <div class="progress">
        <div class="bar"></div >
        <div class="percent">0%</div >
    </div>

    <div id="status"></div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function() {

var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');

$('form').ajaxForm({
    beforeSend: function() {
        status.empty();
        var percentVal = '0%';
        bar.width(percentVal)
        percent.html(percentVal);
    },
    uploadProgress: function(event, position, total, percentComplete) {
        var percentVal = percentComplete + '%';
        bar.width(percentVal)
        percent.html(percentVal);
    },
    complete: function(xhr) {
     bar.width("100%");
    percent.html("100%");
        status.html(xhr.responseText);
    }
}); 

})();       
</script>

</body>
</html>   

我的PHP代码:

<?php
$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
    " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
}
?>

答案 1 :(得分:1)

这是一种方式,我是如何做到的。使用XHR。当我们说话时,我已经启动并运行了

Using HTML5 file uploads with AJAX and jQuery

http://dev.w3.org/2006/webapi/FileAPI/#FileReader-interface

$(':file').change(function(){
            var file = this.files[0];
            name = file.name;
            size = file.size;
            type = file.type;

            if(file.name.length < 1) {

            }
            else if(file.size > 100000) {
                alert("File is to big");
            }
            else if(file.type != 'image/png' && file.type != 'image/jpg' && !file.type != 'image/gif' && file.type != 'image/jpeg' ) {
                alert("File doesnt match png, jpg or gif");
            }
            else { 
                $(':submit').click(function(){
                    var formData = new FormData($('*formId*')[0]);
                    $.ajax({
                        url: 'script',  //server script to process data
                        type: 'POST',
                        xhr: function() {  // custom xhr
                            myXhr = $.ajaxSettings.xhr();
                            if(myXhr.upload){ // if upload property exists
                                myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // progressbar
                            }
                            return myXhr;
                        },
                        //Ajax events
                        success: completeHandler = function(data) {
                            /*
                            * workaround for crome browser // delete the fakepath
                            */
                            if(navigator.userAgent.indexOf('Chrome')) {
                                var catchFile = $(":file").val().replace(/C:\\fakepath\\/i, '');
                            }
                            else {
                                var catchFile = $(":file").val();
                            }
                            var writeFile = $(":file");

                            writeFile.html(writer(catchFile));

                            $("*setIdOfImageInHiddenInput*").val(data.logo_id);

                        },
                        error: errorHandler = function() {
                            alert("Något gick fel");
                        },
                        // Form data
                        data: formData,
                        //Options to tell JQuery not to process data or worry about content-type
                        cache: false,
                        contentType: false,
                        processData: false
                    }, 'json');
                });
            }
    });

答案 2 :(得分:0)

你应该查看一些很酷的jQuery插件,它们可以为你完成这两个流行的插件。

http://www.uploadify.com/

http://www.plupload.com/