PHP的AJAX文件上传错误 [英] Php ajax file upload error

查看:171
本文介绍了PHP的AJAX文件上传错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用ajax上传文件,但我不明白的PHP数据 $ _ FILES ,我得到它的 $ _ REQUEST 。我如何做到这一点。下面是我的jQuery code.Ajax是不工作的文件上传因此没有任何code,这样我可以与现有的$ C $下上传文件合并。

 <脚本>
jQuery的(功能($){
    jQuery的('#BTN)。点击(函数(){

        VAR数据= {},
            蜱= [];

        $('。ajax_elements')。每个(函数(_,ELEM){
            数据[this.id] = THIS.VALUE;

        });


        $阿贾克斯({
            键入:POST,
            网址:app_process.php,
            数据:数据,
            缓存:假的
        })。完成(功能(结果){
            警报(结果);
        });
    });
});
< / SCRIPT>
<表格名称=FRMENCTYPE =的multipart / form-data的>
    <输入类型=文本名称=BB级=ajax_elementsID =一/>
    <输入类型=文件级=ajax_elementsNAME =护照ID =护照/>
    <输入类型=按钮NAME =BTTNID =BTN/>
    < /形式GT;
 

下面是PHP文件code

 < PHP
    如果($ _ REQUEST ['护照'] =''!):
        $ uploaddir ='图像/';
        move_uploaded_file($ _ FILES [文件] [tmp_name的值],$ uploaddir str_replace函数(,_,$ _ REQUEST ['护照']));
    ENDIF;
?>
 

错误信息

  

说明:未定义指数:文件    G:\ XAMPP \ htdocs中\ data_ajax \ app_process.php 在线 5

解决方案

我的建议是看 XMLHtt prequest FORMDATA 文件的API。该 Mozilla开发者网络对所有这些伟大的文档。

这需要测试和调整是在你的开发环境更健壮,但沿着这行的东西可以让你开始...

 <脚本>
$('#BTN)。点击(函数(){

    VAR XHR =新XMLHtt prequest();

    xhr.upload.addEventListener(负荷,函数(E){
        //东西做的时候上传完成
    }, 假);

    xhr.upload.addEventListener(进步,功能(五){
        //此处的东西来处理进度条,进度百分比等。
    }, 假);

    xhr.open('POST','app_process.php,真正的);

    VAR FORMDATA =新FORMDATA();
    。var文件= $('#通行证)获得(0).files [0];

    formdata.append('通行证',文件);

    xhr.send(FORMDATA);

});
< / SCRIPT>
 

和PHP的...

 < PHP
如果(使用isset($ _ FILES ['护照'])){
    $ uploaddir ='图像/';
    $上传= move_uploaded_file($ _ FILES ['护照'] ['tmp_name的值'],$ uploaddir。str_replace函数(,_,$ _ FILES ['护照'] ['名称']))或退出(上传失败。');
} 其他 {
    退出(找不到文件);
}
?>
 

您要发送的文件中的任何其他信息需要被添加到 FORMDATA 对象。这些将出现在PHP $ _ POST 变量。

  formdata.append('场','数据');
 

记住,这些API是没有得到普遍支持的浏览器,所以最好的做法是之前的用户达到了这一点,包括所有常用的功能检测脚本。

您也可以上传功能绑定到文件输入,而不是要求一个按钮,点击...

的变化事件

  $('#通行证)。改变(函数(){...
 

希望有所帮助。

I want to upload file using ajax but i dont get data in php $_FILES and I get it in $_REQUEST. How do I do it. Below is my jquery code.Ajax is not working for file uploading so is there any code so that i can merge with existing code for file uploading process.

<script>
jQuery(function($){ 
    jQuery('#btn').click(function(){

        var data  = {},
            ticks = [];

        $('.ajax_elements').each(function(_, elem) {
            data[this.id] = this.value;

        });


        $.ajax({
            type  : 'POST',
            url   : 'app_process.php',
            data  : data,
            cache : false
        }).done(function(result) {
            alert(result);  
        });
    });
});
</script>
<form name="frm" enctype="multipart/form-data">
    <input type="text" name="bb"  class="ajax_elements" id="one"/>
    <input type="file" class="ajax_elements" name="passport" id="passport" />
    <input type="button" name="bttn" id="btn"  />
    </form>

here is php file code

<?php
    if($_REQUEST['passport']!=''):
        $uploaddir = 'images/';
        move_uploaded_file($_FILES["file"]["tmp_name"], $uploaddir . str_replace(" ","_",$_REQUEST['passport']));
    endif;
?>

error message

Notice: Undefined index: file in G:\xampp\htdocs\data_ajax\app_process.php on line 5

解决方案

My advice would be to look at the XMLHttpRequest, FormData and File APIs. The Mozilla Developer Network have great documentation on all of these.

This needs testing and tweaking to be more robust in your development environment, but something along the lines of this could get you started...

<script>
$('#btn').click(function() {

    var xhr = new XMLHttpRequest();

    xhr.upload.addEventListener("load", function(e){
        // stuff to do when upload is complete
    }, false);

    xhr.upload.addEventListener("progress", function(e){
        // stuff here to handle progress bars, progress percentages etc.
    }, false);

    xhr.open('POST', 'app_process.php', true);

    var formdata = new FormData();
    var file = $('#passport').get(0).files[0];

    formdata.append('passport', file);

    xhr.send(formdata);

});
</script>

And the PHP...

<?php
if (isset($_FILES['passport'])) {
    $uploaddir = 'images/';
    $upload = move_uploaded_file($_FILES['passport']['tmp_name'], $uploaddir . str_replace(" ","_",$_FILES['passport']['name'])) or exit('Upload failed.');
} else {
    exit('File not found');
}
?>

Any additional information you want to send with the file needs to be added to the FormData object. These will appear in the PHP $_POST variable.

formdata.append('field', 'data');

Bear in mind that these APIs are not universally supported in browsers, so best practice is to include all the usual feature detection scripts before the user reaches this point.

You could also bind the upload function to the change event of the file input instead of asking for a button click...

$('#passport').change(function() { ...

Hope that helps.

这篇关于PHP的AJAX文件上传错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆