为什么图像没有复制到文件夹中? [英] Why isn't the image not copied to the folder?

查看:119
本文介绍了为什么图像没有复制到文件夹中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Ajax,PHP.

I'm working with Ajax, PHP.

我想上传图像而不单击提交按钮,并且我正在使用此答案中描述的方法:

I want to upload an image without clicking the submit button and I'm using the approach described in this answer: How to upload file using jquery ajax and php (without clicking any submit button)

但是它不起作用.我需要更改数据类型还是其他?

But it's not working. Do I need to change the data type or something else?

这是我的代码:

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>

推荐答案

您需要使用

You need to use FormData() to send files to server through AJAX. Change your script to:

$.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");
        }
    }
});

这篇关于为什么图像没有复制到文件夹中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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