简体   繁体   English

如何通过jQuery上传图片?

[英]How to upload an image through jQuery?

For past few days i have been struggling to submit a form with jQuery and AJAX.在过去的几天里,我一直在努力使用 jQuery 和 AJAX 提交表单。 The problem i'm facing is to upload the image in the form field.我面临的问题是在表单字段中上传图像。

My form is something like this:我的表格是这样的:

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

and my jQuery script for getting the form value is something like this:我用于获取表单值的 jQuery 脚本是这样的:

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

But this returns all the field values except image one, in case of image is return null.但这将返回除图像一之外的所有字段值,如果图像返回空值。

How do I store in the dataarray?我如何存储在数据数组中?

I want to store so I can send the value to the server through the AJAX.我想存储以便我可以通过 AJAX 将值发送到服务器。

For uploading single image its like this上传单个图像就像这样

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

For multiple images u will have to loop its kinda different对于多个图像,你将不得不循环它有点不同

I have found a similar question, hope it will help you.我发现了一个类似的问题,希望对你有帮助。

Upload image using jquery 使用jquery上传图片

Another option to consider is to use some sort of jQuery plugin to upload images like Cloudinary and include it in your HTML pages :另一个要考虑的选择是使用某种jQuery 插件来上传像 Cloudinary 这样的图像并将其包含在您的 HTML 页面中:

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

and then include all required jQuery files:然后包含所有必需的 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>

try this code, it's work for me.试试这个代码,它对我有用。

 $("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){
        }
    });
});

Try this code.试试这个代码。 using formData()使用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>

serialize() method not able to post file data. serialize() 方法无法发布文件数据。

For sending file using ajax use FormData instead of serializing要使用 ajax 发送文件,请使用 FormData 而不是序列化

HTML5 introduces FormData to allow developers to build forms objects dynamically, and then to send this form object via AJAX. HTML5 引入了 FormData 允许开发者动态构建表单对象,然后通过 AJAX 发送这个表单对象。

your Html你的 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 call 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上传图片.php

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

Try this way.Hope it will help you试试这个方法,希望对你有帮助

Please check the follow the code, which i am using to upload image.请检查我用来上传图片的代码。

$.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");
            }
        });

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

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