jQuery-File-Upload icon indicating copy to clipboard operation
jQuery-File-Upload copied to clipboard

Additional Form Data per File

Open sjg123 opened this issue 14 years ago • 18 comments

I have looked at the different links and the other multiple questions about this but I can't seem to get this to work. I am able to upload the files to dynamic directories and save the file information to a mySQL db but I am having trouble properly storing the additional file data.

I have added the additional form field for title[] as per the wiki. I can see in Firebug that the title array is getting posted. However I can not seem to get the titles to correctly store with their "matching" file. I can store the same title for every file. I have also been successful in storing each title, but it does not necessarily match with the correct file.

I am a little confused since some of the old questions on this seem to have been asked before the code serialized the passed data???

I am also confused about the following paragraph in the wiki. I am not sure if I need to use/adjust this or even exactly where this code is/should be.


"Next we only need to adjust the submit event callback method to gather the form data via the context option, which has been set by the UI version of the plugin inside of the add callback to the upload row:

$('#fileupload').bind('fileuploadsubmit', function (e, data) { var inputs = data.context.find(':input'); if (inputs.filter('[required][value=""]').first().focus().length) { return false; } data.formData = inputs.serializeArray(); });


I have looked at this for few days so I apologize if I am missing the obvious answer. Any help would be appreciated!

sjg123 avatar Mar 11 '12 22:03 sjg123

I've updated the documentation slightly: https://github.com/blueimp/jQuery-File-Upload/wiki/How-to-submit-additional-Form-Data

The text above has been updated to the following:

Next we need to bind a callback to the "submit" event to gather the form data via the upload row context (the context is set by the UI version of the plugin inside of the add callback to the upload row node)

This basically means you add the code after the fileupload widget initialization.

blueimp avatar Mar 14 '12 10:03 blueimp

Thanks! I have it working now. I love your plugin! I'll share step-by-step what I needed to change and where in order to get additional data sent and stored in a mysql db. I spent a couple frustrating days banging on code and searching the docs so it may help someone else.

(*** EDITED MY ORIGINAL POST TO INCLUDE code snippet below in main.js rather than jquery.fileupload-ui per blueimp's suggestion)

You need to make changes in three files, index.php, main.js and upload.class.php

  1. index.php - Add your additional field(s) as detailed in https://github.com/blueimp/jQuery-File-Upload/wiki/How-to-submit-additional-Form-Data under the section for "Setting formData on upload start for each individual file upload"

  2. main.js - Add the code snippet from the above wiki page

$('#fileupload').bind('fileuploadsubmit', function (e, data) {
    var inputs = data.context.find(':input');
    if (inputs.filter('[required][value=""]').first().focus().length) {
        return false;
    }
    data.formData = inputs.serializeArray();
});
  1. upload.class.php

Look for the post function and add your additional field(s) after the foreach (see $_REQUEST['title'] after $upload['error'][$index])

public function post() {
    if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
        return $this->delete();
    }
    $upload = isset($_FILES[$this->options['param_name']]) ?
        $_FILES[$this->options['param_name']] : null;
    $info = array();
    if ($upload && is_array($upload['tmp_name'])) {
        foreach ($upload['tmp_name'] as $index => $value) {
            $info[] = $this->handle_file_upload(
                $upload['tmp_name'][$index],
                isset($_SERVER['HTTP_X_FILE_NAME']) ?
                    $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index],
                isset($_SERVER['HTTP_X_FILE_SIZE']) ?
                    $_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'][$index],
                isset($_SERVER['HTTP_X_FILE_TYPE']) ?
                    $_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'][$index],
                $upload['error'][$index],
                $_REQUEST['title']

            );
        }
    } elseif ($upload || isset($_SERVER['HTTP_X_FILE_NAME'])) {
   .......
  1. upload.class.php

You need to add the new param(s) to the function call after $error param

    protected function handle_file_upload($uploaded_file, $name, $size, $type, $error, $title) {
        $file = new stdClass();
        $file->name = $this->trim_file_name($name, $type);
        $file->size = intval($size);
        $file->type = $type;
        $error = $this->has_error($uploaded_file, $file, $error);
        if (!$error && $file->name) {

Towards the bottom of the handle_file_upload in upload.class.php you need to actually make your db call

                          $file->error = 'abort';
            }
            $file->size = $file_size;
            $this->set_file_delete_url($file);

            // add info to db

            $query = "Insert into tblPhotos (ClientId,PrimaryFlag,PhotoCaption,FileName,DateUploaded) VALUES ('2','0','".$title."','".$name. "','" . date('Y-m-d') ."')";   

            $result = mysql_query($query);

            if (mysql_errno() <> 0)
            {
                $errmsg ="SQL ERROR: Uploaded Photo Info NOT added.<BR>Query: ". $query. "<BR> Error #". mysql_errno() . " : " . mysql_error();
                trigger_error($errmsg,E_USER_ERROR);

            }


        } else {
            $file->error = $error;
        }
        return $file;
    }

Of course you will need to start your session and make your mysql db connections and create your mysql table but I have not shown that here. (trigger_error is a custom error handler I have. You will need to replace that with your own error handler.)

sjg123 avatar Mar 14 '12 18:03 sjg123

Thanks for posting your solution for others to find. The only addition I have for your post is that I would rather add the JS code to main.js instead of changing jquery.fileupload-ui.js, which you might want to override with updates in the future.

blueimp avatar Mar 15 '12 01:03 blueimp

Thanks, I have modified my original resolution post to update main.js rather than the fileupload-ui.js.

sjg123 avatar Mar 15 '12 14:03 sjg123

EDIT: Amazing plug-in btw!

I had a bit of an issue w/ the javascript in main.js, I had to use:

$('#fileupload').bind('fileuploadsubmit', function (e, data) { var inputs = data.context.find(':input'); if (inputs.filter('[required][value=""]').first().focus().length) { return false; } data.formData = data.form.serializeArray(); //console.log(data.form.serializeArray()); });

I'm terrible w/ javascript so please let me know if I've done something really dumb, lol

j0ney3 avatar Apr 02 '12 16:04 j0ney3

How does the new "handle_form_data method" recently added change this process? In other words, what now needs to be done in order to pass additional form data?

ghost avatar May 08 '12 05:05 ghost

For the client-side, nothing changed and the docs here are still the way to go: https://github.com/blueimp/jQuery-File-Upload/wiki/How-to-submit-additional-Form-Data

For the PHP implementation, you can use the following approach and edit index.php accordingly:

<?php
// ...
class CustomUploadHandler extends UploadHandler {
    protected function handle_form_data($file, $index) {
        // Handle form data here, e.g.:
        // $_POST['description'][$index]
    }
}
$upload_handler = new CustomUploadHandler();
// ...

blueimp avatar May 08 '12 07:05 blueimp

Thank you so much for your prompt reply. I'm very grateful.

Steve

-----Original Message----- From: Sebastian Tschan [mailto:[email protected]] Sent: 08 May 2012 8:25 AM To: lancasterlad Subject: Re: [jQuery-File-Upload] Additional Form Data per File (#1094)

For the client-side, nothing changed and the docs here are still the way to go: https://github.com/blueimp/jQuery-File-Upload/wiki/How-to-submit-additional-Form-Data

For the PHP implementation, you can use the following approach and edit index.php accordingly:

<?php
// ...
class CustomUploadHandler extends UploadHandler {
    protected function handle_form_data($file, $index) {
        // Handle form data here, e.g.:
        // $_POST['description'][$index]
    }
}
$upload_handler = new CustomUploadHandler(); // ...

Reply to this email directly or view it on GitHub: https://github.com/blueimp/jQuery-File-Upload/issues/1094#issuecomment-5569135

ghost avatar May 08 '12 07:05 ghost

This thread should be pinned somehow.

I've got around to grab that form-data (thanks to poster and your wiki) and and made available through json after the file was submitted. However if the page got refresh, the data is purged.

I believed if the uploaded template got refreshed, it goes through the get() function, but I am not sure how I could retain them?

Thanks in advance!

bigmoof avatar May 29 '12 06:05 bigmoof

I am facing problem adding multiple additional data fields. Works fine if only one additional data field is added but if more than one data field is added example: title, description etc during the Post for each file only the last input field's value is binded with the form data, When i check the Post event in the firebug i see only the value from the input field named "descrip". i have another field named "title" but its getting lost. I would really appreciate your help. Thanks

Here is what i added and did.

callback function is as before:

$('#fileupload').bind('fileuploadsubmit', function (e, data) {
var inputs = data.context.find(":input");
data.formData = inputs.serializeArray();
});

This is what i see in firebug console for Post event.

Source -----------------------------64222494627506 Content-Disposition: form-data; name="descrip" ss -----------------------------64222494627506 Content-Disposition: form-data; name="files[]"; filename="arrow_left.png" Content-Type: image/png ‰PNG......etc

shadab1418 avatar Aug 10 '12 09:08 shadab1418

@shadh the same to you in python, have you solved it? share it please!

goog avatar Oct 22 '12 00:10 goog

@shadh @goog I'm getting the same thing - were either of you able to find a solution?

Bochenski avatar Oct 31 '12 10:10 Bochenski

@Bochenski here is https://github.com/goog/couchdb-uploader

goog avatar Nov 01 '12 03:11 goog

I do what sjg123 says and I get this error...even though it does upload successfully. SyntaxError: Unexpected token <

I am getting the error because my variable $title isn't being requested like it should

kraigballa avatar Dec 13 '12 18:12 kraigballa

Is there a way to do it using Java on Server side?

femosso avatar Mar 05 '13 00:03 femosso

yes, how do you retrieve formData from the request in java? It is not in a parameter... :|

lisadesouza89 avatar Apr 15 '13 12:04 lisadesouza89

This code fragment works properly on almost all browsers, but IE 8 doesn't support parameters passed this way.

$('#fileupload').bind('fileuploadsubmit', function (e, data) { var inputs = data.context.find(":input"); data.formData = inputs.serializeArray(); }); I got next error: WARNING: Can't verify CSRF token authenticity.

Now, I guess is because this "serializeArray()" function is overriding something. JIC, I've tested it on IE9 and IE10 and they don't have any issue.

Has anyone ran into this issue? would you please share your suggestions?

Thanks!.

richardjaldin avatar Apr 30 '13 22:04 richardjaldin

How can I add a radio button group to let the user to select ''before or after" for each file? I want to get which radio button was choosed for each file in server side also.

See the name is piptype and it is not array. Do i need to give it as array like piptype[]? How can i get this in server side?

My Upload template has

            {% if($('#ddlUploadContext').val()=="something") { %}
            <label><input type="radio" name="piptype" value="before">Before<label>
            <label><input type="radio" name="piptype" value="after">After<label>
        {% } %}

w2sadmin avatar Jun 07 '14 22:06 w2sadmin