【问题标题】:uploading files with jquery $.ajax and php使用 jquery $.ajax 和 php 上传文件
【发布时间】:2012-04-21 16:30:11
【问题描述】:

我希望在用户使用 $.ajax 在输入文件中选择文件时异步上传文件。但是接收调用的php返回索引未定义。 jquery代码如下:

$("#urlimatge").change(function(){
            var filename = $("#urlimatge").val();
            $.ajax({ 
                type: "POST",
                url: "utils/uploadtempimg.php",
                enctype: 'multipart/form-data',
                data: {'urlimatge' : filename },
                success: function(response){
                     alert(response);
                }
            }); 

        });

以及调用调用的 php:

$image =  new gestorimatges();
$target_path = $image->uploadTemp($_FILES['urlimatge']['name'],$_FILES['urlimatge']['tmp_name']);

谢谢

【问题讨论】:

    标签: php jquery ajax html


    【解决方案1】:

    您不能将 $_FILE 从 AJAX 传递给 PHP。

    我建议使用plugin

    它会让你的生活更轻松 :) Here is a video tutorial to help too

    【讨论】:

    • 好的,谢谢,我可以传递足够的参数来上传文件吗,例如名称或网址?我会试试插件谢谢。
    • 是的,你可以传递额外的参数和一切,你只需添加参数:{anything: 'youwant'}
    【解决方案2】:

    您可能想为此使用uploadify 之类的工具。

    【讨论】:

    【解决方案3】:

    您无法使用 AJAX 上传文件,但您可以使用 iframe,这样您就不必刷新当前页面。

    许多人对插件束手无策,但您可以很容易地自己完成,并且具有 AJAX 请求的所有功能。

    不使用 AJAX 函数,而是将表单提交到隐藏的 iframe,并附加一个 load 事件处理程序,因此当提交表单时,您有一个回调函数,其中实际上包含服务器响应 ( iframe 加载后的 HTML)。

    例子:

    HTML --

    <form action="..." method="post" encrypt="application/x-www-form-urlencoded" target="workFrame" >
        <input type="file" name="file" />
        <input type="submit" />
    </form>
    <iframe id="workFrame" src="about:blank" style="display:none;"></iframe>
    

    JS--

    $(function () {
        $('form').on('submit', function () {
            //check if the form submission is valid, if so just let it submit
            //otherwise you could call `return false;` to stop the submission
        });
    
        $('#workFrame').on('load', function () {
    
            //get the response from the server
            var response = $(this).contents().find('body').html();
    
            //you can now access the server response in the `response` variable
            //this is the same as the success callback for a jQuery AJAX request
        });
    });
    

    【讨论】:

    • 感谢我使用了类似的 iframe 解决方案。我调用 iframe 并用 jquery 修改 action 的值。
    • 以下对我不起作用:我正在使用多文件上传器来选择多个文件。文件仅通过表格发送。它现在在我的 Firefox 浏览器中打开一个新的“标签”......
    • ___Javascript 是:____
    • @rajeev 您的代码很难作为 cmets 阅读,我建议针对您的问题创建一个问题。
    • @Jasper,嗨,当通过iFrame 上传时,页面不会在选项卡中显示加载符号,例如:demos.9lessons.info/progress/index.php?success?而在 Facebook 中上传到墙上的图片却没有在选项卡中显示任何加载符号。
    猜你喜欢
    • 2017-02-15
    • 1970-01-01
    • 2010-12-29
    • 2015-05-11
    • 2017-08-25
    • 2014-05-07
    相关资源
    最近更新 更多