views:

476

answers:

1

Before starting, note that I have to update a website that is not mine, so I can't redo the whole logic. If I were to do this I would do it differently.

I have a cakephp application with a form with a lot of fields. In this form you can browse for a file and save it asynchronously. Here is how it's done:

<input type="file" name="data[FileUpload][file]" id="myFileToUpload">
<a id="pickFile" href="#">Upload&nbsp;Now</a>
<script type="text/javascript">
    $('#pickFile').click(function(e){
     e.preventDefault();
      $.post( 
       "/admin/FileUploads/saveFromFlash/<?php e($session->id()) ?>", 
       { data:$("#myFileToUpload").val() },
       function(data){
        $("#returnedContentFromAjax").html(JSON.stringify(data));
       }, 
       "json"
      );
    });

</script>

The function called mainly does this:

$this->FileUpload->save($this->data)

but this always returns false and "No upload passed". Here is the line creating the error message:

if (!isset($this->data['FileUpload']['file'])) {
        $this->setUploadError('No upload passed');
    return false;
}

I have no clue how to send this "$this->data['FileUpload']['file']" via ajax... I guess this is the key problem since I don't know what object to pass here:

{ data:$("#myFileToUpload").val() },

I've been on it all evening, any help would be greatly appreciated

+3  A: 

In summary: javascript can't access the contents of a file selected for upload.

This article deals with getting an "ajax effect" for your file uploads: http://stackoverflow.com/questions/543926/is-it-possible-to-ajax-a-file-upload

russau
is it possible to use something like jquery form even if the uploader is already in a form?
marcgg
Yes, jquery Form will grab the action of your existing form and post to that. There an example for file upload in the code samples: http://malsup.com/jquery/form/#code-samples
russau
thanks, I'll try to implement this
marcgg