2

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

thecodedeveloper.com
  • 3,220
  • 5
  • 36
  • 67
marcgg
  • 65,020
  • 52
  • 178
  • 231
  • 2
    #myFileToUpload is a INPUT type="FILE" element? you can't access the contents of the file from javascript. Have a look at this question: http://stackoverflow.com/questions/543926/is-it-possible-to-ajax-a-file-upload – russau Jul 20 '09 at 01:49
  • argh... well it's the end for me ^^ thanks for the answer – marcgg Jul 20 '09 at 01:51
  • Could I use the form plugin even if the file upload is in another form? – marcgg Jul 20 '09 at 01:52

2 Answers2

3

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: Is it possible to use Ajax to do file upload?

Community
  • 1
  • 1
russau
  • 8,928
  • 6
  • 39
  • 49
  • is it possible to use something like jquery form even if the uploader is already in a form? – marcgg Jul 20 '09 at 01:55
  • 1
    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 Jul 20 '09 at 01:59
0

try uploadify, it is JQuery Ajax uploading system. Easy to use. http://www.uploadify.com/

Teodorescu
  • 148
  • 5
  • 15