Pass an image through AJAX [duplicate]

2019-03-18 02:33发布

问题:

This question already has an answer here:

  • How can I upload files asynchronously? 31 answers

Basically I want to pass a image file with ajax on submitting a form and retrieve the image and send it by email as an attachment file:

Here's the form :

<form role="form" action="" name="devis" id="devis" method="post" enctype="multipart/form-data" class="form-horizontal">
    <fieldset>
        <div class="form-group">
            <label class="control-label col-md-4" for="societe">Company</label>
            <div class="col-md-8">
                <input type="text" class="form-control input-md col-md-8" name="societe" value="" maxlength="" id="societe">
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-4" for="message"><span class="required">* </span>Message</label>
            <div class="col-md-8">
                <textarea rows="5" name="message" class="form-control input-md col-md-8" maxlength="" required="" style="resize:none;" id="message"></textarea>
            </div>
        </div>
        <div class="form-group" id="input_file">
            <label class="control-label col-md-4" for="image_input_field">Logo</label>
            <div class="col-md-8">
            <div class="input-group uploaddiv">
                <span class="input-group-btn">
                    <span class="btn btn-default btn-file">
                        Parcourir <input type="file" id="image_input_field" name="file">
                    </span>
                </span>
                <input type="text" class="form-control" readonly="">
            </div>
            </div>
        </div>
    <div class="form-group">
    <div class="form-actions col-md-9 col-md-offset-3 text-right">
        <input type="submit" value="Envoyer" name="" class="btn btn-primary" id="submit">
        <input type="reset" value="Annuler" name="" class="btn btn-default" id="reset">
        </div>
    </div>
    </fieldset>
</form>

I can't seem to find what's the error in my code ! Here's the AJAX call :

jQuery(document).on("click", "#submit", function(e) {
      e.preventDefault();
      var fileInput = document.getElementById('image_input_field');
      var file = fileInput.files[0];
      var formData = new FormData();
      formData.append('file', file);
      // console.log(file);

      var societe = $("input#societe").val();
      var message = $("textarea#message").val();
      jQuery.ajax({
        url: "ajax.php",
        type: "post",
        data: {
           'file': file,
           'module' : 'ajax_data_form',
           'societe': societe,
           'message': message
        },
        cache: false,

        success: function(reponse) {
          if(reponse) {
            alert(reponse);
            // console.log(reponse);
            // jQuery('#devis').trigger("reset");
          } else {
            alert('Erreur');
          }
        }
      });
     });

And here's the ajax.php:

<?php
if( isset($_POST['module']) && $_POST['module'] == "ajax_data_form" )
{
     var_dump($_FILES);
}

回答1:

$.ajax({
    type: "POST",
    url: pathname,
    data: new FormData($('#devis')[0]),
    processData: false,
    contentType: false,
    success: function (data) {
        $("#divider").html(data);
    }
});

and get the file data normally in $_FILES[];



回答2:

can you try it

<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
  var fileInput = document.getElementById('image_input_field');
  var file = fileInput.files[0];
  var formData = new FormData();
  formData.append('file', file);
  // console.log(file);

  var societe = $("input#societe").val();
  var message = $("textarea#message").val();

      $.ajax({
        url: "ajax.php",
        type: "POST",
        data: "file="+file,
        cache: false,

        success: function(reponse) {
          if(reponse) {
            alert(reponse);

            // console.log(reponse);
            // $('#devis').trigger("reset");
          } else {
            alert('Erreur');
          }
        }
      });
 }); });
</script>

In ajax.php

just write

 echo 'something';


回答3:

As you may know already, it is not possible to process file uploads via ajax calls, it will be possible once HTML5 FILE I/O Api is ready and implemented by major browsers.

You can use jQuery iframe post form plugin to post data in iframe so user experience will be similar to ajax call (partial update of page).

Here is the link: https://github.com/dogzworld/iframe-post-form

Description: "This jQuery ajax upload plugin creates a hidden iframe and sets the form's target attribute to post to that iframe. When the form is submitted, it is posted (including the file uploads) to the hidden iframe. Finally, the plugin collects the server's response from the iframe."

As mentioned you can send response from the server and display updates on your webpage accordingly. There has to be a demo page but it is not working as of now.

You can also use it for file uploads.

Calling Example:

jQuery('#frmId').iframePostForm({
    json : true,
    post : function () {
        //return true or false
        return true;
    },
    complete : function (response) {
        //complete event
        console.log(response);
    }
});


回答4:

Using a Jquery Plugin Called Jquery Form plugin Link

I would suggest to simply submit the form using jquery and what ever data you want you can keep them in hidden fields.

$("#devis").ajaxSubmit(options); 
return false;

The you can easily get the file in the php page like this

$ImageTempname  = $_FILES['ImageFile']['tmp_name'];
$ImageFilename  = $_FILES['ImageFile']['name'];
$ImageType      = $_FILES['ImageFile']['type'];

and so on.....