duanaiguang1960 2017-04-24 00:52
浏览 129
已采纳

使用ajax上传文件

I´ve been looking at all the answers i could find in here, but none seems to work for me, not sure why.

I´m trying to upload a file using ajax, but the file never gets to the $_FILES array in PHP, i only makes it to the $_POST array but it won´t let me get the name or size of the file. I've tried every single solution answered here but none seems to solve my problem and i'm not sure why, i think there is something i'm not seeing. If anyone can help me that would be awesome.

THE HTML CODE

<form name='formuploadgraphic'>
     <input type='file' name='archivo1' id='archivo1' onchange='subegraphic()'>
</form>

THE JS/AJAX CODE

function subegraphic()
{
    var formData = new FormData();
    formData.append("archivo1", $("#formuploadgraphic")[0]);

    $.ajax({
        url: "subegraphic.php",
        type: "post",
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        async: true
    })
     .done(
         function(data)
         {
             alert(data);
         }
     );
}

THE PHP CODE

<?php
    $upload_folder ='graphics';
    $nombre_archivo = $_FILES['archivo1']['name'];
    $tipo_archivo = $_FILES['archivo1']['type'];
    $tamano_archivo = $_FILES['archivo1']['size'];
    $tmp_archivo = $_FILES['archivo1']['tmp_name'];
    $extension = pathinfo($_FILES['archivo1']['name'], PATHINFO_EXTENSION);
    $archivador = $upload_folder . '/' . $nombre_archivo;
    echo $nombre_archivo;
?>

This is the reply from the php if i use that code:

"
Notice: Undefined index: archivo1 in C:\xampp\htdocs\airpost\home\subegraphic.php on line 4

Notice: Undefined index: archivo1 in C:\xampp\htdocs\airpost\home\subegraphic.php on line 5

Notice: Undefined index: archivo1 in C:\xampp\htdocs\airpost\home\subegraphic.php on line 6

Notice: Undefined index: archivo1 in C:\xampp\htdocs\airpost\home\subegraphic.php on line 7

Notice: Undefined index: archivo1 in C:\xampp\htdocs\airpost\home\subegraphic.php on line 8
"

If anyone can tell what is the problem with my code that would be grate. Thx in advance.

PS: upload files is ON in the php.ini

  • 写回答

2条回答 默认 最新

  • doudouwd2017 2017-04-24 01:39
    关注

    From the Code Snippet you posted, your jQuery selector is pointing to an undefined element

    Change

    formData.append("archivo1", $("#formuploadgraphic")[0]);
    

    to

    formData.append("archivo1", $("#archivo1").prop('files')[0]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多