Search code examples
javascriptjqueryjquery-file-upload

how to upload a file using jquery


i have a browse input field without a form.

<div class="bottom_wrapper clearfix">
    <div class="message_input_wrapper">
    <!--<input placeholder="Type your message here..." class="message_input"><a href="#"><img src="/public/img/camera.png" alt="camera" /></a>!-->
        <input type="hidden" name="contactid" id="contactID" value="">
        <input class="message_input" id="msg" name="msg" placeholder="Type your message here..." />
        <input type="hidden" id="image" value="<%= userid %>">
        <div class="image-upload">
            <label for="file-input">
                <img src="/public/img/camera.png"/>
            </label>
            <input id="file-input" name="file" type="file"/>
        </div>
    </div>
    <div class="send_message">
        <div class="icon"></div>
        <input type="submit" name="submit" id="submit" value="Send" onclick="submitFunction(document.getElementById('contactID').value)">
    </div>
</div>

when i click on camera image a browse option will executeenter image description here.

and here is my function which is i used for simple text posting but i want to modify it to send file as well.

<script type="text/javascript">
    function submitFunction(contactid) {
        var image = document.getElementById('image').value;
        var msg = document.getElementById('msg').value;
        var contactid = document.getElementById('contactID').value;
        var data = {};
        data.message = msg;

        $.ajax({
            method: "POST",
            url: "/messages/" + contactid,
            data: {message: msg}
        })
        .done(function (msg1) {
            $("#msg").val("");
            $(".chat_window  ul").append('<li class="message right appeared"><div class="avatar"><img src="http://example.com/getUserImage/' + image + '/60"/></div><div class="text_wrapper"><div class="text">' + msg + '</div></div></li>');
        });
    }
</script>

Solution

  • To upload image using $.ajax method, you need to create FormData object.

    eg. var formData = new FormData();

    then add your image and other data into formData object

    formData.append("image",$('input[type=file]')[0].files[0]);
    

    and then pass this formData as parameter or data to jquery ajax method.

    $.ajax({
            method: "POST",
            url: "/messages/" + contactid,
            data: formData,
           // THIS MUST BE DONE FOR FILE UPLOADING
           contentType: false,
           processData: false
        })