使用ajax上传表单文件

时间:2014-04-22 10:06:49

标签: javascript php jquery ajax

我想上传文件并将其保存在带有jquery ajax的服务器上。我已经尝试过但它没有用。它不想处理它。这就是我的工作:

html代码

<form action="" method="post" enctype="multipart/form-data">
        <input type="file" name="submit_file" id="submit_file" required >
        <input type="text" name="submit_message" id="submit_message">          
 </form>
 <a href="javascript:upload();" ><img  src="img/join_btn.png" /></a>

验证和ajax

<script type="text/javascript">
    function upload()
    {   
        var $submit_file = $("#submit_file").val();
        var $submit_message = $("#submit_message").val();


        if($submit_file == '')
        {
            alert('please choose your picture');
            $('#submit_file').focus();
            //return false;
        }
        else if($submit_message == '')
        {
            alert('please write message');
            $('#submit_message').focus();
            //return false
        }
        else
        {
            uploadFile();
        }
    }
</script>

<script type="text/javascript">
    function uploadFile()
    {
        var $submit_file = '';
        var $submit_message = '';

        if($("#submit_file").val()) {$submit_file = $("#submit_file").val()};
        if($("#submit_message").val()) {$submit_message = $("#submit_message").val()};

        $.ajax( 
            {
                global: false,
                cache: false,
                url: "./proc_intro.php",
                type: "POST",
                data:
                {

                    submit_file: $submit_file,
                    submit_message: $submit_message,

                },
                dataType: "json",
                success: function(json) {
                    if (json.result == "success") 
                    {
                        //alert('success');
                        setTimeout(function(){
                            showLayer('main_submit');
                        },1000);
                    }
                    else
                    {
                        alert('server error');
                    }
                }   
            }
        ); 
    }
</script>

proc_intro.php文件

<?php
    $submit_file = $_REQUEST[submit_file];
    $submit_message = $_REQUEST[submit_message];


  $allowed_filetypes = array('.jpg','.gif','.bmp','.png'); 
  $max_filesize = 524288; 
  $upload_path = './images/'; 


$filename = $_FILES[$submit_file]['name']; 
   $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); 

   if(!in_array($ext,$allowed_filetypes))
      die('The file you attempted to upload is not allowed.');


if(filesize($_FILES['submit_file']['tmp_name']) > $max_filesize)
      die('The file you attempted to upload is too large.');


if(!is_writable($upload_path))
      die('You cannot upload to the specified directory, please CHMOD it to 777.');

if(move_uploaded_file($_FILES['submit_file']['tmp_name'],$upload_path . $filename))
   {
       echo '{"result":"success"}';
   }else
   {
        echo '{"result":"fail"}';
   }
?>

如何使用ajax正确上传文件? 你有什么主意吗?提前谢谢。

2 个答案:

答案 0 :(得分:0)

检查出来

function progressHandlingFunction(e){
    if(e.lengthComputable){
        $('progress').attr({value:e.loaded,max:e.total});
    }
}

function uploadFile()
{
    var $submit_file = '';
    var $submit_message = '';

    if($("#submit_file").val()) {$submit_file = $("#submit_file").val()};
    if($("#submit_message").val()) {$submit_message = $("#submit_message").val()};
   var formData = new FormData($('form')[0]);
    $.ajax( 
        {
            global: false,
            cache: false,
            url: "./proc_intro.php",
            type: "POST",
            data:   formData ,
            xhr: function() {  // Custom XMLHttpRequest
        var myXhr = $.ajaxSettings.xhr();
        if(myXhr.upload){ // Check if upload property exists
            myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
        }
        return myXhr;
    },
    //Ajax events
  //  beforeSend: beforeSendHandler,
    success:function()
    {
        alert('success');
    },
    error: function()
    {
        alert('error');
    },
    // Form data
    //Options to tell jQuery not to process data or worry about content-type.
    cache: false,
    contentType: false,
    processData: false   
        }
    ); 
}

答案 1 :(得分:0)

这可能不是完整的答案,但摆脱了second comma in:

data:
{
   submit_file: $submit_file,
   submit_message: $submit_message**,**
}