【发布时间】:2018-09-09 15:06:36
【问题描述】:
我正在使用以下代码,用户可以在其中上传一个或多个文件并删除这些文件。所有数据都存储在form_data。
到目前为止,我无法使文件上传功能正常工作。
index.php
<input id="avatar" type="file" name="avatar[]" multiple />
<button id="upload" value="Upload" type="button">upload</button>
<div class="preview">
</div>
<div class="return_php"></div>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script>
$(document).ready(function () {
var form_data = new FormData();
var number = 0;
/* WHEN YOU UPLOAD ONE OR MULTIPLE FILES */
$(document).on('change', '#avatar', function () {
console.log($("#avatar").prop("files").length);
len_files = $("#avatar").prop("files").length;
for (var i = 0; i < len_files; i++) {
var file_data = $("#avatar").prop("files")[i];
form_data.append(file_data.name, file_data);
number++;
var construc = '<img width="200px" height="200px" src="' +
window.URL.createObjectURL(file_data) + '" alt="' + file_data.name + '" />';
$('.preview').append(construc);
}
});
/* WHEN YOU CLICK ON THE IMG IN ORDER TO DELETE IT */
$(document).on('click', 'img', function () {
var filename = $(this).attr('alt');
var newfilename = filename.replace(/\./gi, "_");
form_data.delete($(this).attr('alt'))
$(this).remove()
});
/* UPLOAD CLICK */
$(document).on("click", "#upload", function () {
$.ajax({
url: "upload.php",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with form_data
type: 'post',
success: function (data) {
$('.return_php').html(data);
}
})
})
});
</script>
上传.php
<?php
//upload.php
var_export($_FILES); // this final output that i want to upload
?>
【问题讨论】:
-
您面临的问题是什么? enctype 属性也用于表单而不是输入
-
请检查我的 ajax 代码是否以正确的方式发送正确的数据?
-
这两个错误来自“未定义的索引:form_data”和“为 foreach() 提供的参数无效”
-
好的。所以这意味着这个form_data在foreach($_FILES['form_data']['name']中是无效的。尝试在上传文件的开头打印&_FILES数组,你会得到正确的名称