Javascript 如何通过jQuery上传图片?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44283986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:25:19  来源:igfitidea点击:

How to upload an image through jQuery?

javascriptphpjqueryhtmlajax

提问by Racoon

For past few days i have been struggling to submit a form with jQuery and AJAX. The problem i'm facing is to upload the image in the form field.

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

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 将值发送到服务器。

回答by Racoon

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

对于多个图像,你将不得不循环它有点不同

回答by Dina Kaiser

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

回答by Hitesh Vala Ahir

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

回答by Dinesh undefined

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>

回答by Nidhi

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

试试这个方法,希望对你有帮助

回答by Deepak Patil

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