0

I've been trying to upload a File with Ajax but the FormData is always empty.

This is the code i'm using to:

<html>
<head>
<link rel="stylesheet" href="../website/css/bootstrap.min.css">
</head>
<body>
    <form id="providerForm">
        <input id="fileI" class="form-control" name="fileI" type="file" />
        <button id="newProviderButton" type="submit" class="btn btn-success"
            value="Enviar">Enviar</button>
    </form>
</body>
<script type="text/javascript"
    src="https://code.jquery.com/jquery-latest.min.js"></script>
<script
    src="http://formvalidation.io/vendor/formvalidation/js/formValidation.min.js"></script>
<script
    src="http://formvalidation.io/vendor/formvalidation/js/framework/bootstrap.min.js"></script>
<script>
    var providerId = "";
    function newProvider() {

        var a = $("#providerForm")[0];
        var b = $("#providerForm");
        var c = new FormData($(b)[0]);
        var d = document.getElementById('providerForm');
        var dataT = new FormData(d);
        var params = $('#providerForm').serializeArray();
        c.append("file",$($(a).find("#fileI"))[0]); 
        $.each(params, function(i, val) {
            dataT.append(val.name, val.value);
            console.log(val.name + ": " + val.value);
        });
        $.ajax({
                    type : "POST",
                    beforeSend : function(request) {
                        request.setRequestHeader("Content-Type",
                                "multipart/form-data");
                    },
                    url : "../services/user/profile/upload/image",
                    data : dataT,
                    cache : false,
                    contentType : false,
                    processData : false,
                    success : function(msg) {
                        if (msg.message == "OK") {
                            mAlert({
                                container : $("#providerForm"),
                                message : 'Usuario registrado correctamente',
                                type : 'success',
                                okButton : 'OK'
                            });
                        }
                    },
                    statusCode : {
                        401 : function() {
                            window.location.replace("../entrance.jsp");
                        }
                    }
                });

    }
    $(document).ready(function() {
        $("#providerForm").on('reset',function(){
            $(this).data('formValidation').resetForm(true);
        });
         $('#providerForm').formValidation({
                framework: 'bootstrap',

                icon: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {}
            })
         .on('success.form.fv', function(e) {
                // Prevent form submission
                e.preventDefault();

                var $form = $(e.target),
                    fv    = $(e.target).data('formValidation');

                // Do whatever you want here ...

                // Then submit the form as usual
                newProvider();
                //fv.defaultSubmit();
            });
    });
</script>
</html>

You can see the result here.

enter image description here

As you can see I tried getting the HTMLElement througt different methods and even appending the element individually the result id FormData = {}

EDIT:

I need the FormData encoding in multipart/form-data format

2 Answers 2

1

The best way to upload files is not with Ajax, but if you want to do that, you can follow the belong tutorial:

http://blog.teamtreehouse.com/uploading-files-ajax

The best way to upload files is the traditional method, making a form with enctype="multipart/form-data" refreshing the website, is very simple but same the best way to do that.

Regards

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

6 Comments

Thanks Radames, so what do you think is the best way?
Sergio, the best way to upload files is the traditional method, making a form with enctype="multipart/form-data" refreshing the website, is very simple but same the best way to do that.
Ok. I was trying to not refresh the page but I think I will have to. Thanks!
A suggestion, you can separate in 2 steps your form, the first part you can send all information via ajax, and send to the user to another section particularly to upload the file.
Nice, but I was trying to do something faster. The app is for a work environment. I'm thinking on call submit method programatically to avoid another click or page.
|
0

If you are using jQuery (as tagged), try using form.serialize() in place of your $.each dataT append.

6 Comments

Well I need the FormData in multipart/form-data encoding.
Good point, have you tried: var formData = new FormData(); formData.append( 'file', $('#fileI').files[0] );
I see you use "c.append("file",$($(a).find("#fileI"))[0]); " but isnt the extra $() unnecessary?
var formData = new FormData(); formData.append( 'file', $('#fileI').files[0] ); gets right the File but does not append it to formData. And yes, the extra $ is unnecessary I just tried all the possibilities. I don't know if the problem is with the FormData object or the <input type="file">
Thats strange, sorry I wasnt any help! though it might be a long shot but the docs say that i takes a 3rd optional parameter used for forms, which is the form file name? developer.mozilla.org/en-US/docs/Web/API/FormData/append
|

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.