【问题标题】:How to upload file using jquery ajax and php (without clicking any submit button)如何使用 jquery ajax 和 php 上传文件(不点击任何提交按钮)
【发布时间】:2014-01-16 14:41:27
【问题描述】:

我有这样的表格:

<form method="post" class="form_cnvc">
   <p><input type="text" name="f_nm" value="" placeholder="type your first name"></p>
   <p><input type="text" name="l_nm" value="" placeholder="type your last name"></p>
   <div class="dropfile visible-lg">
   <input type="file" id="image_file_input" name="image_file_input">
   <span>Select Images(.jpg , .png, .bmp files) </span>
   </div>
   <p class="submit"><input type="submit" name="submit" value="post"></p>
 </form>

我希望当用户选择一张图片时,它会自动提交到我的 PHP 页面,以便我可以将它保存在数据库中并返回带有图片缩略图的 insert_id。

我想用 jQuery 来做,但做不到。

PHP代码是:

【问题讨论】:

  • 你不应该这样做。当你上传你甚至不想上传的东西时,它真的很烦人,因为你点击了错误。我总是建议通过按钮上传。

标签: javascript php jquery ajax file-upload


【解决方案1】:

简单,在输入元素上使用更改触发器并在内部执行 ajax 请求:

$("#image_file_input").change(function() { 
    $.ajax({
        url: "my-target-url.php",
        type: "post",
        dataType: 'json',
        processData: false,
        contentType: false,
        data: {file: $("#image_file_input").val()},
        success: function(text) {
            if(text == "success") {
                alert("Your image was uploaded successfully");
            }
        },
        error: function() {
            alert("An error occured, please try again.");         
        }
    });   
});

创建一个 url 或路由并在 url: tag (domain/file.php) 中输入它,然后编码服务器端的东西:

function processFileUpload() {
    if(count($_FILES) > 0) {
        foreach($_FILES as $file) {
            //DO whatever you want with your file, save it in the db or stuff...
            //$file["name"];
            //$file["tmp_name"];
            //Insert here bla blubb
            echo "success";
        }
    }
    die();
}

【讨论】:

  • 如果没有某种 BLOB 数据(可以使用 HTML5 文件 API 创建),您无法单独使用 ajax 上传文件。
  • @up 刚刚注意到我的脚本中有一个错误,$(#image_file_input).val() 应该是: $("#image_file_input").val() -> 缺少引号 我编辑了帖子.但是,如果它仍然无法正常工作,您应该发布更多输出、错误、查看浏览器的 JavaScript 控制台并尝试是否调用了 PHP 端的脚本。找到错误并向我提供更多信息。
  • @Steini dataType: 'json' is generated conflict with php answer also data: {file: $("#image_file_input").val()}, 似乎与 PHP $_FILES 不对应说,非常感谢您的提示
猜你喜欢
  • 2014-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-23
  • 1970-01-01
  • 1970-01-01
  • 2019-07-28
  • 2017-04-26
相关资源
最近更新 更多