【问题标题】:Why isn't the image not copied to the folder?为什么图像没有复制到文件夹中?
【发布时间】:2016-03-24 13:11:49
【问题描述】:

我正在使用 Ajax,PHP。

我想在不点击提交按钮的情况下上传图片,我正在使用此答案中描述的方法:How to upload file using jquery ajax and php (without clicking any submit button)

但它不起作用。我是否需要更改数据类型或其他内容?

这是我的代码:

jQuery/Ajax

$(document).ready(function(){
var b = new FormData($(this).closest("form")[0]);
b.append('image', $('input[type=file]')[0].files[0]);
  $("#imgInput").change(function(){
    $.ajax({
      url: "test.php",
      type: "post",
      datatype: 'json',
      processData: false,
      contentType: false,
      data: b,
      success: function(text){
        if(text== "success"){
          alert("Image uploaded");
        }
      },
      error: function(){
        alert("Not uploaded");
      }
    });
  });
});

test.php

<?php
  $filename=$_FILES["image"]["name"];
  $filetmp=$_FILES["image"]["tmp_name"];
  $filetype=$_FILES["image"]["type"];
  $filepath="images/".$filename;
  move_uploaded_file($filetmp, $filepath);
?>

HTML

<form name="form1" method="post" enctype="multipart/form-data">
  <table>
    <tr>
      <td><input type="text" name="name" placeholder="Enter your name" /></td>
      <td rowspan="3"><div class="propic"><img id="" /></div>
        <input id="imgInput" type="file" name="image" /></td>
    </tr>
    <tr>
      <td><input type="text" name="username" placeholder="Enter username"/></td>
    </tr>
    <tr>
      <td><input id="digits" type="text" name="phone" maxlength="10" placeholder="Enter your phone no."/></td>
    </tr>
    <tr>
      <td><input type="password" name="password" maxlength="12" placeholder="Enter password"/></td>
      <td><input id="button" type="submit" name="submit" value="Sign Up" /></td>
    </tr>
  </table>
</form>

【问题讨论】:

  • 你需要调试你的脚本。在 test.php 中输入 var_dump($_FILES) 并检查该请求,例如在 chrome 控制台中。
  • 您需要使用FormData()
  • 我在哪里以及如何使用它@PraveenKumar
  • 是什么让你认为move_uploaded_file是罪魁祸首?

标签: php jquery html ajax


【解决方案1】:

您需要使用FormData() 通过AJAX 向服务器发送文件。将您的脚本更改为:

$.ajax({ 
    url: "test.php",
    type: "POST",
    data: new FormData($(this).closest("form")[0]),  // This is the main place you need.
    contentType : false,
    async: false,
    processData: false,
    cache: false,
    success: function(text) {
        if(text== "success"){
          alert("Image uploaded");
        }
    }
});

【讨论】:

  • 如果可能,请完整编辑 Ajax 代码。我不知道您使用的选择器。我会感谢你的。
  • 让你的表单就像id="myForm",然后像$("#myForm")一样调用
  • @VikasKumar 0. 不要使用 sir 这个词。 1. form 不能嵌套。 2. 图像input 应该嵌套在表单中。 3. 图像input 只能有一个 表单作为其父级。
  • @pr0metheus 同意你的观点,但他需要了解正确的使用和可扩展的使用。如果你给id 并使用,是的,这是正确的方法之一,它有效,但它不能针对不同的形式进行扩展,比如说?
  • @PraveenKumar 真实
【解决方案2】:

如果您只是想让它工作,我推荐 Ravishanker Kusuma 的 Hayageek jQuery File Upload plugin我通常不推荐插件,但这个非常棒。它几乎可以为您完成所有工作。

http://hayageek.com/docs/jquery-upload-file.php

他将这个过程分解为四个简单的步骤,基本上是这样的:

寻找 //1 //2 //3:

<head>
  // (1) Load the js files (note that it requires jQuery, which we also load)
    <link href="http://hayageek.github.io/jQuery-Upload-File/uploadfile.min.css" rel="stylesheet">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="http://hayageek.github.io/jQuery-Upload-File/jquery.uploadfile.min.js"></script>   // (1)
</head>
<body>
    <div id="fileuploader">Upload</div>  // (2) Create DIV
    <script>
        $(document).ready(function(){
            $("#fileuploader").uploadFile({  // (3) initialize plugin
                url:"my_php_processor.php",
                fileName:"myfile"
            });
        });
    </script>
</body>

最后(第四)步是创建一个与上面在 jQuery 代码中指定的名称相同的 PHP 文件(在本例中为 my_php_processor.php)来接收和处理该文件:

my_php_processor.php:

<?php
    $output_dir = "uploads/";
    $theFile = $_FILES["myfile"]["name"];
    move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);

注意PHP中的myfile$_FILES["myfile"])和jQuery代码块中指定的文件名myfile之间的关系。

在 Hayageek 网页上,研究 Server 选项卡上的 upload.php 示例。

请注意,您还可以使用dynamicFormData 将其他变量传递给my_php_processor.php 处理器文件。请参阅另一个示例:

$("#fileuploader").uploadFile({
    url:"my_php_processor.php",
    fileName:"myfile",
    dynamicFormData: function(){
        return {
            //my_php_processor.php will receive POST vars below
            newSubj: $("#newSubj").val(),
            newBody: $("#newBody").val(),
        };
    },
    onSuccess:function(files,data,xhr,pd){
        //files: list of files
        //data: response from server
        //xhr : jquery xhr object
        alert(xhr.responseText); //displays data ECHOd by `my_php_processor.php`
    }
});

my_php_processor.php:

<?php
    $n = $_POST['newSubj'];
    $b = $_POST['newBody'];
    $uploadedFile = $_FILES["myfile"]["name"];
    //etc.
    echo 'This will display in the alert box';

jsFiddle Sample Code - Click on Image Example

【讨论】:

  • 这看起来不错。选择图像时这会起作用吗? :)
  • 你是什么意思,when the image is selected?如果您的意思是,您是否可以通过单击显示的图像触发显示 jQuery 文件上传字段/按钮的弹出窗口,然后是的 - 与我的回答中的 jsFiddle 示例代码非常相似。 请参阅答案中的其他 jsFiddle 如果您的意思是,此插件是否适用于图像,那么是的 - 您可以指定接受或不接受的文件/图像类型。惊人的插件。仔细阅读 Kusuma 的网站 - 他用很少的词涵盖了所有内容。
  • 要限制插件接受的允许文件类型,请参阅stackoverflow.com/questions/11832930/…
  • 不错。谢谢你的解释。
猜你喜欢
  • 2018-07-20
  • 2023-01-27
  • 1970-01-01
  • 1970-01-01
  • 2018-08-04
  • 2016-06-09
  • 1970-01-01
  • 2020-08-03
  • 1970-01-01
相关资源
最近更新 更多