简体   繁体   中英

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 execute 在此处输入图片说明 .

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>

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
    })

You need to serailize the data to be sent, so you can either use jQuerys $('form').serialize() or use FormData() here are the API docs

So a simple example would be something like this:

<form class="bottom_wrapper clearfix" form id="chatForm" enctype="multipart/form-data" action="/postMessage">
    <div class="message_input_wrapper">
        <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">
    </div>
</div>

So your input fields should be wrapped in a form to serialize all the form inputs to data, then simply post all the message together.

$('#chatForm').submit(function(e) {
    e.preventDefault();

    var formData = new FormData(this);

    $.ajax({
        type: 'POST',
        url: $(this).attr('action'),
        data:formData,
        cache:false,
        contentType: false,
        processData: false,
        success: function(data) {
          // Success handling code
        },
        error: function(data) {
          // Error handling code
        }
    });
});

Then it is down to your server to handle the message with all the parts

I just want to make @Sachin K answer easier to understand. it's true that you have to make formData Object to post/upload a file or an image.

first, create formData.

var formData = new FormData();

if in a form (your form id is 'myForm')

var formData = new FormData($('#myForm')[0]);

second, add input file into formData.

formData.append("image",$('#file')[0]);

* 'file' is your input file id.

if your input file is in a form (myForm), you can skip this step.

The last, post proccess.

$.ajax({
    url: "input_data.php",
    type: "POST",
    data : formData,
    contentType: false,
    cache: false,
    processData:false,
    success:function(res){
        alert('image post succesfully!');
    }
});

I found it somewhere and its working fine. May be it helps to you.

<script type="text/javascript">`$('#submit').on('click', function() {
var file_data = $('#file-input').prop('files')[0];   
var form_data = new FormData();                  
form_data.append('file', file_data);
alert(form_data);                             
$.ajax({
            url: 'upload.php', // point to server-side PHP script 
            dataType: 'text',  // what to expect back from the PHP script, if anything
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,                         
            type: 'post',
            success: function(php_script_response){
                alert(php_script_response); // display response from the PHP script, if any
            }
 });

}); `

And upload.php

<?php

if ( 0 < $_FILES['file']['error'] ) {
    echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
    move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM