如何通过jquery上传图像

时间:2017-05-31 11:48:46

标签: javascript php jquery html ajax

过去几天,我一直在使用jquery和ajax提交表单。我面临的问题是在表单字段中上传图像

我的表格是这样的

<form action="#" method="GET" role="form" enctype="multipart/form-data">
 <input type="text" placeholder="Name" name="name">
 <input type="file" name="img" multiple>
  <button type="submit">Submit </button>
</form>

我的用于获取表单值的jquery脚本就是这样的

 $("form").submit(function (event) {
            $.dataArray = $(this).serializeArray(); // array of form data
            console.log($.dataArray);
            event.preventDefault();
        });

但是在图像的情况下返回除了图像1之外的所有字段值都返回null。 我如何存储在dataarray? 我想存储所以我可以通过AJAX将值发送到服务器 请有人帮助我,谢谢你!

6 个答案:

答案 0 :(得分:6)

如上传单张图片

     <html>
        <head>
            <meta charset="UTF-8">
            <title>AJAX image upload with, jQuery</title>
            <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
            <script type="text/javascript">
                $(document).ready(function (e) {
                    $('#upload').on('click', function () {
                        var file_data = $('#file').prop('files')[0];
                        var form_data = new FormData();
                        form_data.append('file', file_data);
                        $.ajax({
                            url: 'http://localhost/ci/index.php/welcome/upload', // point to server-side controller method
                            dataType: 'text', // what to expect back from the server
                            cache: false,
                            contentType: false,
                            processData: false,
                            data: form_data,
                            type: 'post',
                            success: function (response) {
                                $('#msg').html(response); // display success response from the server
                            },
                            error: function (response) {
                                $('#msg').html(response); // display error response from the server
                            }
                        });
                    });
                });
            </script>
        </head>
        <body>
            <p id="msg"></p>

            <input type="file" id="file" name="file" multiple />
            <button id="upload">Upload</button>
        </body>
    </html>

对于多个图像,你必须循环其有点不同的

答案 1 :(得分:2)

我发现了一个类似的问题,希望它会对你有所帮助。

Upload image using jquery

另一个需要考虑的选择是使用类似Cloudinary的某种jQuery plugin to upload images并将其包含在HTML页面中:

 <script src='jquery.min.js' type='text/javascript'></script>
 <script src='jquery.cloudinary.js' type='text/javascript'></script>

然后包含所有必需的jQuery文件:

<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.ui.widget.js' type='text/javascript'></script>
<script src='jquery.iframe-transport.js' type='text/javascript'></script>
<script src='jquery.fileupload.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>

答案 2 :(得分:0)

试试这段代码,这对我有用。

 $("form").submit(function (event) {

    var form_data = new FormData($(this));

    $.ajax({
        url : url, 
        type : 'POST',
        data : form_data,
        processData: false,  // tell jQuery not to process the data
        contentType: false,
        success : function(resp){
        }
    });
});

答案 3 :(得分:0)

试试这段代码。使用formData()

$("form").submit(function (event) {
            
    var formData = new FormData($(this));

    $.ajax({
          url: url,
          type: 'POST',
          data: formData,
          async: false,
          success: function (data) {
              //success callback
          },
          cache: false,
          contentType: false,
          processData: false
         });

   });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="GET" role="form" enctype="multipart/form-data">
 <input type="text" placeholder="Name" name="name">
 <input type="file" name="img" multiple>
  <button type="submit">Submit </button>
</form>

答案 4 :(得分:0)

serialize()方法无法发布文件数据。

使用ajax发送文件时使用FormData而不是序列化

HTML5引入了FormData,允许开发人员动态构建表单对象,然后通过AJAX发送此表单对象。

您的Html

<form action="upload_image.php" id="form_img" method="GET" role="form" enctype="multipart/form-data">
 <input type="text" placeholder="Name" name="name">
 <input type="file" name="img" multiple>
  <button type="submit">Submit </button>
</form>

AJAX致电

<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $("#form_img").submit(function(e){
            e.preventDefault();
            var formData = new FormData($("#form_img")[0]);

            $.ajax({
                url : $("#form_img").attr('action'),
                type : 'POST',
                data : formData,
                contentType : false,
                processData : false,
                success: function(resp) {
                    console.log(resp);                        
                }
            });
        });
    });

</script>

<强> upload_image.php

print_r($_FILES) //check you get file data or not

试试这种方式。希望它可以帮到你

答案 5 :(得分:0)

请检查以下代码,我用来上传图片。

$.ajax({
            url: UPLOADURL,   // Url to which the request is send
            type: "POST",       // Type of request to be send, called as method
            data:  new FormData(this),// Data sent to server, a set of key/value pairs representing form fields and values
            contentType: false,// The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
            cache: false,// To unable request pages to be cached
            processData:false,// To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
            success: function(data)// A function to be called if request succeeds
            {

                data = JSON.parse(data);
                console.log(data);
                if(data.status == "Success"){
                    attachmentListing();
                    //$("#mailerMessage").html(data.data.mailStatus);
                    //$("#mailerMessage").fadeIn();
                    setTimeout(function () {
                        $("#mailerMessage").fadeOut();
                    },5000);
                }else{
                    toastr.warning(data.status);

                }
                $("#ajaxloader").addClass("hideajaxLoader");
            },
            error: function (jqXHR, errdata, errorThrown) {
                log("error");
                $("#ajaxloader").addClass("hideajaxLoader");
            }
        });