使用ajax / jquery将图像上传到文件夹

时间:2017-07-06 03:27:24

标签: php jquery ajax

我试图使用ajax,jquery和php将图像上传到文件夹,但问题是我不知道如何将文件输入值发送到我的php文件,当我运行我的文件时代码我收到以下消息:

  

undefined index archivo

这是我的ajax调用(PD。所有其他参数都正常工作,我只对文件输入值有问题)

function Registrar() {
      var cat = $('#cat').val();
      var nom = $('#name').val();
      var desc = $('#description').val();
      var image = $('#archivo').val(); 
     //Also tried with this, to remove the fakepath string... $('input[type=file]').val().replace(/C:\\fakepath\\/i, '') 

      $.ajax({
        url: '../../class/upload.php',
        method: 'POST',
        data: { categoria: cat, nombre: nom, descripcion: desc, archivo: image, activo: act, disponible: disp, precio: prec },
        success: function (data) {
          console.log(data);
        } 
      });
    }

PHP文件:

<?php

    $categoria = $_POST['categoria'];
    $nombre = $_POST['nombre'];
    $descripcion = $_POST['descripcion'];
    $img = $_POST['archivo'];
    $activo = $_POST['activo'];
    $disponible = $_POST['disponible'];
    $precio = $_POST['precio'];
    $IdCategoria = 0;
    $filepath = "";

    //Imagen

    if($categoria=="Piano") {
        $IdCategoria = 1;
        $filepath = "../Files/Productos/Piano/".$img; 
    }

    $filetmp = $_FILES['archivo']['tmp_name'];
    move_uploaded_file($filetmp, $filepath);

    echo $IdCategoria.$nombre.$descripcion.$filepath.$activo.$disponible.$categoria.$precio;


?>

我的HTML的重要部分:

<form id="registerForm" method="post" role="form" enctype="multipart/form-data" >
<input name="archivo" id="archivo" style="width: 70%;" name="textinput" class="btn btn-block" type="file" onchange="showimagepreview(this)" />

编辑:showimagepreview

function showimagepreview(input) {

            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {

                    document.getElementsByTagName("img")[0].setAttribute("src", e.target.result);
                }
                reader.readAsDataURL(input.files[0]);
            }
        }

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

发送您的表单数据:

var formData = new FormData($("form")[0]);

$.ajax({
        url: '../../class/upload.php',
        method: 'POST',
        data: formData,
        success: function (data) {
          console.log(data);
        } 
      });

你必须得到$_FILES的文件,你不能在$_POST的PHP代码中得到它。

答案 1 :(得分:1)

更改此

  $img = $_POST['archivo'];

$_FILES['archivo'];

$_POST

无法接收文件对象

答案 2 :(得分:1)

这是你的解决方案

HTML

<form id="registerForm" method="post" enctype="multipart/form-data">
    <input name="archivo" id="archivo" style="width: 70%;" class="btn btn-block" type="file" onchange="PreviewImage(this)" />
    <img id="uploadPreview" />
    <button type="submit">Submit</button>

Java脚本

function PreviewImage() {
    var oFReader = new FileReader();
    oFReader.readAsDataURL(document.getElementById("image").files[0]);
    oFReader.onload = function (oFREvent) {
        document.getElementById("uploadPreview").src = oFREvent.target.result;
   };
};

//ajax

$("#registerForm").submit(function(event) {  
    var formData = new FormData($(this)[0]);
    if ($(this).valid()) {
        $.ajax({
            url         : '../../class/upload.php',
            type        : 'POST',
            data        : formData,
            contentType : false,
            cache       : false,
            processData : false,
            success: function(e) {alert(e)  },
            error       : function(x, t, m) {},
        });         
    }
 });

PHP

<?php
    echo "<pre>"; print_r($_FILES);echo "</pre>"; die; //this will show you the file transfered by form.
    $categoria = $_POST['categoria'];
    $nombre = $_POST['nombre'];
    $descripcion = $_POST['descripcion'];
    $img = $_POST['archivo'];
    $activo = $_FILES['activo'];
    $disponible = $_POST['disponible'];
    $precio = $_POST['precio'];
    $IdCategoria = 0;
    $filepath = "";

    //Imagen

    if($categoria=="Piano") {
        $IdCategoria = 1;
        $filepath = "../Files/Productos/Piano/".$img; 
    }

    $filetmp = $_FILES['archivo']['tmp_name'];
    move_uploaded_file($filetmp, $filepath);

    echo $IdCategoria.$nombre.$descripcion.$filepath.$activo.$disponible.$categoria.$precio;


?>