dpzbh1779 2016-10-12 03:18
浏览 22
已采纳

通过ajax上传文件时,它总是返回[作为文件信息

I have looked through many different questions and I still haven't been able to locate the flaw in my code. I basically am attempting to upload a file to the server using html/ajax and php for the server side. Below is my code:

 //HTML
<div class="col-sm-6">
  <div class="">
     <input name="bugType" type="text" class="bugType">
  </div>
 </div>
 <div class="col-sm-6">
    <div class="upload">
       <input name="bugImage" type="file" class="bugImage">
    </div>
 </div>

//JS 
$("#addBug").on('click', function (event) {
    event.preventDefault();
    var bugType = $('input[name="bugType"]').val();
    var imageName = $('input[name="bugImage"]');
    fd = new FormData();
    fd.append("type", "add");
    fd.append("imageName", imageName);
    fd.append("bugType", bugType);
    $.ajax({
        url: 'classes/bug-class.php',
        type: "POST",
        dataType: "json",
        data: fd ,
        enctype: 'multipart/form-data',
        contentType: false, 
        processData: false,  
        success: function (data) {
            alert("SUCCESS");
            alert(data);
        },
        error: function (data) {
            alert("FAILURE");
            console.log(data);
        }
    });
});



//PHP
$type = $_POST['bugType'];
$image = $_POST['imageName'][0];
echo $image; //PRINTS OUT [

If I change:

  $image = $_FILES['imageName']
  echo $image // PRINTS OUT ""

Thanks for the help!

//EDIT

 FileList {0: File, length: 1}
 0
 :
 File
 lastModified
 :
 1475177716000
 lastModifiedDate
 :
 Thu Sep 29 2016 14:35:16 GMT-0500 (CDT)
 name
 :
 "17-3.png"
 size
 :
 187682
 type
:
"image/png"
webkitRelativePath
:

"" proto : File length : 1 proto : FileList

var_dump($_FILES) // output -> array(0)

//WORKING

had to change to this:

  fd.append("imageName", imageName[0])

and then it worked!

  • 写回答

1条回答 默认 最新

  • dssnh86244 2016-10-12 03:31
    关注

    You directly send the element to your SERVER.

    var imageName = $('input[name="bugImage"]');
    
    
    var imageName = $('input[name="bugImage"]')[0].files; 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度