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

3
  • 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: stackoverflow.com/questions/543926/… Commented Jul 20, 2009 at 1:49
  • argh... well it's the end for me ^^ thanks for the answer Commented Jul 20, 2009 at 1:51
  • Could I use the form plugin even if the file upload is in another form? Commented Jul 20, 2009 at 1:52

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

2 Comments

is it possible to use something like jquery form even if the uploader is already in a form?
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: malsup.com/jquery/form/#code-samples
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.