Dev DOS
Dev DOS

Reputation: 1068

symfony upload file without saving it on the server

I'm using symfony and I try to import csv file to just get it content. First I added the field importFile to my Entity(ps: the field should not be stored in DB):

  /** @var  UploadedFile  $importFile*/
private $importFile;

/**
 * @return UploadedFile
 */
public function getImportFile()
{
    return $this->importFile;
}

/**
 * @param UploadedFile $importFile
 */
public function setImportFile(UploadedFile $importFile = null)
{
    $this->importFile = $importFile;
}

then I added the field to my formType:

   ->add('importFile',FileType::class, array('label' => false,'attr'=>['id'=>'upload','style'=>'']))

and in my view I aded the form field: {{ form_row(form.importFile) }}

--edit

I get the upload file on my view, but when I submit the form with ajax: -- edit2

var form = $("[id^=" + "form" + "]");
$.ajax({
        url: url,
        type: 'POST',

        data: new FormData(form),
        contentType: false,
        cache: false,
        processData:false,
        success: function (data, status)
        {
          alert('rr');
        },
        error: function (xhr, desc, err)
        {


        }
    });

I don't get the imported file on my request:

dump($request->files->all());

it returns empty .

What should I do to read the file ?

Upvotes: 1

Views: 1097

Answers (2)

Inform-all
Inform-all

Reputation: 168

Symfony 4 has a out of the box solution for this. Try using FormData to upload files.

Upvotes: 0

simshaun
simshaun

Reputation: 21466

File inputs are not serialized by jQuery's .serialize() method. If you need to send file data to the server via AJAX, you have to resort to other methods.

A couple options are:

  1. Using FormData if your target audience's browsers support the File API.
  2. Using a jQuery plugin like jquery-form which can handle file uploads.

Upvotes: 1

Related Questions