Search code examples
phpajaxsymfonymultipartform-data

Accessing FormData file on the PHP server (symfony)


My problem is that I don't know how to get the file and file name on the server side after making ajax request with FormData. Let me add that it works for strings on the other hand. I also see the file and details in the request via FireBug.

Here is my code:

JavaScript:

var form = document.getElementById('file-form');
var fileSelect = document.getElementById('file-select');
var uploadButton = document.getElementById('upload-button');


// Get the selected files from the input.
var files = fileSelect.files;
// Create a new FormData object.
var formData = new FormData();

var myArray = [];
// Loop through each of the selected files.
for (var i = 0; i < files.length; i++) {
var file = files[i];
console.log(file.name);
myArray[i] = file.name;

// Check the file type.
if (!file.type.match('image.*')) {
continue;
}

 // Add the file to the request.
formData.append('photos[]', file, file.name);
}


var xhr = new XMLHttpRequest();
// Open the connection.
xhr.open('POST',
'http://localhost/amsprojektgit/amsprojekt/admin/web/fileupload', true);

xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
alert('Files uploaded');
} else {
alert('An error occurred!');
}
};

xhr.send(formData);

Server side PHP (Symfony2 container)

public function fileUpload(Request $request)
{

$upload = $_POST;
$logger = $this->get('logger');
$logger->info($upload);
$logger->error('');

die();
}

The response via FireBug looks like this:

-----------------------------269272101016568 Content-Disposition: form-data; name="photos"; filename="elektpolaniec2.jpg" Content-Type: image/jpeg

ÿØÿà�JFIF��H�H��ÿá@Exif��II*����������������¬������r������z��(������� ��������������2������� ������ ��� ��1�(���©��i�������$�� ������0220� ����0100 ������������ ����Ñ�� ������� ����X������Ù������í������������ ��"�������'��� �P��� ��������������������������� ������� ����!��¢��������£�������£�������¤��������¤��������¤��������¤����)��¤� ������¤��������¤��������¤�������� ¤�������� ¤������������������������1������9��(�����������A������÷������H����� �H������2014:02:28 11:05:03�Panasonic�DMC-FX01�PaintShop Pro 15,00���������������������������2013 :06:20 15:42:46�2013:06:20 15:42:46�

It doesn't log anything. Do you have an idea how can I access filenames of the files sent and the content of files themselves?

Thank you for the anser.


Solution

  • Uhm.. In plain PHP the files are stored in a temporary directory and the file information is served through the $_FILES array.

    In Symfony we don't wish to use the superglobal array's directly but we could for example use the Request object. For file uploads you should read this.