Подтвердить что ты не робот

Передайте изображение через AJAX

В принципе, я хочу передать файл изображения с помощью ajax при отправке формы и получить изображение и отправить его по электронной почте в виде файла вложения:

Здесь форма:

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

Я не могу найти, что ошибка в моем коде! Здесь вызов AJAX:

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

И здесь ajax.php:

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

Ответ 1

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

и получить данные файла обычно в $_FILES[];

Ответ 2

можете попробовать?

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

В ajax.php

просто напишите

 echo 'something';

Ответ 3

Использование плагина JQuery, подключенного к JQuery Ссылка

Я бы предложил просто отправить форму с помощью jquery и какие бы то ни было данные, которые вы хотите сохранить в скрытых полях.

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

Вы можете легко получить файл на странице php, как этот

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

и т.д.

Ответ 4

Как вы уже знаете, невозможно обрабатывать загрузку файлов через аякс-вызовы, это будет возможно после HTML5 FILE I/O Api готов и реализован основными браузерами.

Вы можете использовать плагин jQuery iframe post form для отправки данных в iframe, поэтому пользовательский интерфейс будет похож на ajax-вызов (частичное обновление страницы).

Вот ссылка: https://github.com/dogzworld/iframe-post-form

Описание: "Этот плагин для загрузки jQuery ajax создает скрытый iframe и устанавливает атрибут target для отправки в этот iframe. Когда форма отправляется, она отправляется (включая загрузку файлов) в скрытый iframe. Наконец, плагин собирает ответ сервера из iframe."

Как уже упоминалось, вы можете отправлять ответ с сервера и отображать обновления на своей веб-странице соответственно. Должна быть демонстрационная страница, но она пока не работает.

Вы также можете использовать его для загрузки файлов.

Пример вызова:

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