使用ajax和php上传文件

Uploading a file using ajax and php

本文关键字:文件 php ajax 使用      更新时间:2023-09-26

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

任何伪代码、示例或教程都将不胜感激。

演示网址:--

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

你可以从这个url下载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!";
}
?>

这是一种方法,也是我如何做到的。使用XHR。当我们谈论时,我已经启动并运行了它

使用AJAX和jQuery 上传HTML5文件

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

$(':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');
                });
            }
    });

您可能应该看看一些很酷的jQuery插件,它们可以为您完成这项工作,这两个流行的插件是。

http://www.uploadify.com/

http://www.plupload.com/