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

3
我正在尝试使用ajax、jquery和php将图片上传到文件夹,但问题是我不知道如何将我的文件输入值发送到php文件。当我运行代码时,会出现以下消息:
“未定义的索引文件”
这是我的ajax调用(所有其他参数都正常工作,我只有在文件输入值方面遇到问题):
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)" />

EDIT: 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]);
            }
        }

我该如何解决这个问题?

可能是重复问题:https://dev59.com/HmAg5IYBdhLWcg3wG3wK - Abdul Rafay
你能展示一下你的“showFilePreview”函数吗?它可能有你需要的解决方案。它使用了FileReader吗? - Garr Godfrey
@GarrGodfrey 是的,我使用了FileReader,我已经将那段代码添加到我的帖子中了。 - User1899289003
@AbdulRafay 我正在尝试使用那段代码,现在我没有收到任何错误消息,但是现在似乎我的函数没有执行,当我提交表单时,我的页面只重新加载了。 - User1899289003
3个回答

2

下面是将表单数据发送的方法:

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

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

在php代码中,您必须使用$_FILES获取文件,而不能使用$_POST


那么我应该在 $_POST[' '] 中放什么来发送数据呢?我的输入框的名称吗? - User1899289003
你可以将输入名称属性作为键放入 $_POST[] 中。 - Himanshu Upadhyay
我遇到了上述问题...现在我没有收到任何错误消息,但是我的页面只是重新加载,没有显示我的回显行。 - User1899289003
我上面编写的代码应该放在你的ajax函数中。 - Himanshu Upadhyay
我需要用你的代码替换我的ajax代码,对吧? - User1899289003
是的 @User1899289003。 - Himanshu Upadhyay

1

改变这个

  $img = $_POST['archivo'];

to

$_FILES['archivo'];

文件对象无法在 $_POST 中接收到。


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>

JavaScript
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;


?>

1
这里也有同样的问题,没有打印出回显行。只是重新加载页面。 - User1899289003

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接