I am having trouble uploading a picture file via AJAX.
Web:
<div>
<form id="birdi_image_form">
<input type="file" name="birdi_image" id="birdi_image" ></input>
</form>
<input type="text" name="species"></input>
<textarea name="comments"></textarea>
</div>
<div id="debug"></div>
<script type="text/javascript">
jQuery(function($){
$('#birdi_image').change(function(){
var ima = new FormData($('#birdi_image_form')[0]);
$.ajax({
url:"/bird/bird_scripts/fu.php",
type:"post",
data: ima,
processData: false,
dataType:"text",
success:function(data, textStatus, jqXHR) {
$('#debug').text(data);
}
});
});
});
</script>
/bird/bird_scripts/fu.php:
<?php
$imagedir = '/images';
$tmpfname = tempnam($imagedir, "b_");
echo var_dump($_POST);
if (move_uploaded_file($_FILES['birdi_image']['tmp_name'], $tmpfname)) {
echo "File is valid, and was successfully uploaded.n";
} else {
echo "Upload failed";
}
?>
From looking around online I was expecting to find contents in my $_FILES
variable, but this is empty. Dumping out the $_POST
var to the screen like in the example gives me the following. $_POST['birdi_image']
gives me NULL
.
array(68) { [“——WebKitFormBoundaryYCAoI8shwgBavjJP
Content-Disposition:_form-data;_name”]=> string(339) “”birdi_image”;
filename=”test.jpg” Content-Type: image/jpeg ����JFIFdd��
ExifMMbj(1r2��i��B@’B@’Adobe Photoshop
CS2 Windows2008:06:24 11:11:48��b�g”
[“?o��(�ci��R��Μꟑ���]T��z���”]=> string(82) “���
f�zߠ����i���/��v��E~��[,�Y
y{R���������E%���Q����5.��IE���N�����Ο�̿4~R��……………Upload failed.
�s�������1l�G����-���߿�enu'=�v�z���=?Ҳ���"
["�{��<o��ӗ�M��ysnʨo87~;l���۔�"]=> string(172) "�<��t�2~���O�S
�����t���㵺C�}E������}��I�d]c���y}#�����C,�Z��־��V��ynʿ��?�g�*����o��ٌ�.}�y����}��z����w^�]�m�u������z>�37�_C긵��K𭪣�Y-{��뺷��M���ul��Y�"
["c�yhHp����"]=> string(152)
"��[-���1�]��|�����۽Q��e���o�~��g������u�.���A��t�]�3�W�ד��b���}>�����%��K���Ѳ�3���zX��qZ��}u��sc�
���N� ^-w�7���r� ����c��=?δX�j" ["C�uw���-��"]=> string(57)
"���m��w��������ѩ���������k��r����m�t�62rIk���m�ߗV��}" ["�"]=>
string(384)
"!�<��B���6*�c��劷Q���uF*��U��������ď,�
I have uploaded files before by using a complete form submit. This is the first time I am trying to do it with AJAX. It looks like the data is getting to the server, but I can’t seem to make any sense of it from the server side. As you can see in the code I expected $_FILES['birdi_image']
to exist but it doesn’t. Am I doing something completely wrong?
Thanks
2
Answers
You have to set the content type to false, otherwise jQuery will set one(the wrong one) for you
I struggled with this also – it’s just not as easy as it should be. I finally found a guy who did it right, and studied his code.
Ravi Kusuma’s jQuery File Upload
In the end, because Kusuma wrote a plugin, I just used his code/plugin. Why re-invent the wheel? He’s got everything solved, right down to sending extra data along with the uploaded file.