doulangchao8934 2014-06-05 19:32
浏览 36
已采纳

使用ajax和表单提交上传图像

I want to upload an image to the server using Ajax, but there is a problem. Would somebody please help me what is wrong here. I could submit the image using submit form but not ajax. here is my code:

html:

<div id="uploadPic" onclick="getFile()">
Select a photo to upload
</div>
<form name="myForm" id="avatar_form" enctype="multipart/form-data" method="post" action="">
<div style='height: 0px;width:0px; overflow:hidden;'>
<input id="upfile" class="botpic" type="file" name="avatar" value="upload" required="" onchange="sub1()">
</div>
</form>

javascript:

function getFile(){
   document.getElementById("upfile").click();
}
function sub1(){
var photo = document.getElementById("upfile");
    var file = photo.files[0];
    data = new FormData();
data.append('file', file);
$.ajax({
    url: 'url',
    data: data
    enctype: 'multipart/form-data',
    processData: false,  // do not process the data as url encoded params
    contentType: false,   // by default jQuery sets this to urlencoded string
    type: 'POST',
    success: function ( output ) {
       document.getElementById('picTmp').innerHTML = output;;
    }
});
}

PHP code:

if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
    $fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
 .......
}
  • 写回答

5条回答 默认 最新

  • dongshadu4498 2014-06-06 17:34
    关注

    Finally I found where the problem is. Maybe it is useful for others struggling with ajax uploading a file.Now it is working perfectly. The solution is:

    In the php code, all the ["avatar"] should be replaced with ["file"] as we are sending the file specified as file in ajax.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助