简体   繁体   English

如何使用jQuery上传文件

[英]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. 要使用$ .ajax方法上传图像,您需要创建FormData对象。

eg. 例如。 var formData = new FormData();

then add your image and other data into formData object 然后将您的图像和其他数据添加到formData对象中

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

and then pass this formData as parameter or data to jquery ajax method. 然后将此formData作为参数或数据传递给jquery ajax方法。

$.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 您需要对要发送的数据进行序列化,因此可以使用jQuerys $('form')。serialize()或使用FormData(),这是API文档

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. 我只是想让@Sachin K答案更容易理解。 it's true that you have to make formData Object to post/upload a file or an image. 的确,您必须使formData对象发布/上传文件或图像。

first, create formData. 首先,创建formData。

var formData = new FormData();

if in a form (your form id is 'myForm') 如果采用表单(您的表单ID为“ myForm”)

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

second, add input file into formData. 其次,将输入文件添加到formData中。

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

* 'file' is your input file id. *'file'是您的输入文件ID。

if your input file is in a form (myForm), you can skip this step. 如果输入文件的格式为(myForm),则可以跳过此步骤。

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']);
}

?> ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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