0

Я сделал стилизованную загрузку файлов вот так:

$("#buttonFileLabel").click(function() {
  $("#avatar").trigger("click");
});

$("#avatar").change(function() {
  var v = $("#avatar").val();
  v = v.substr(12);
  $("#textFileLabel").html("Выбранный файл: " + v);
});

$("#bavatar").click(function() {
  var setting = $("#avatar").val();
  $.post("dal/changeSettings.php", {
    s: "avatar",
    c: setting
  }, function(data) {
    alert(data);
  });
});
#fileLabel {
  border: 1.5px solid #a64fa6;
  padding: 10px;
}

#buttonFileLabelContainer {
  display: table-cell;
}

#buttonFileLabel {
  transition-duration: 0.7s;
  background-color: #a64fa6;
  color: white;
  border: 2px solid #a64fa6;
}

#textFileLabel {
  width: 100%;
  text-align: center;
  vertical-align: middle;
  display: table-cell;
}

.margin-min {
  margin: 5px 0;
}

.setting {
  width: auto;
  padding: 10px;
  border-bottom: 3px solid #a64fa6;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="setting">
  <h1 class="margin-min">Ваша аватарка:</h1>
  <div id="fileLabel">
    <span id="textFileLabel">Выберите файл!</span>
    <div id="buttonFileLabelContainer"><button id="buttonFileLabel">Выберите файл!</button></div>
  </div>
  <input type="file" id="avatar" style="display: none;" name="avatar">
  <button class="accept" id="bavatar">Изменить аватарку</button>
</div>

Отправляю все это с помощью AJAX и JQuery. Я получаю нечто такое когда пытаюсь получить значения моего <input type='file'> (var setting = $("#avatar").val();): C:\fakepath\download.png. Как мне сделать так, чтобы при отправлении файл появлялся в массиве $_FILES? Или так нельзя сделать?

1 ответ 1

1

Отправлять файл нужно так:

var formData = new FormData();    
formData.append('c', $("#avatar").prop('files')[0]);
formData.append('s', 'avatar');

$.ajax({
  url: 'dal/changeSettings.php',
  data: formData,
  processData: false,
  contentType: false,
  type: 'POST',
  success: function(data){
    alert(data);
  }
});

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.