我必须使用表单数据发送多个文件,但是我的代码无法正常工作,有人可以告诉我哪里出了问题。
$('#fileupload').on('change', function() {
var to_user_id = $(this).data('touserid');
var chat_id = $(this).data('chat_id');
var formData = new FormData();
$.each($('input[type=file]')[0].files, function(i, value) {
formData.append('file[' + i + ']', value.files[0]);
});
//console.log(formData);
formData.append('to_user_id', to_user_id);
formData.append('chat_id', chat_id);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
dataType: 'json',
processData: false,
contentType: false,
cache: false,
success: function(data) {
//console.log(data);
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" name="upload_form" id="upload_form" enctype="multipart/form-data" action="upload.php">
<input type="file" name="fileupload[]" id="fileupload" multiple data-touserid="'+to_user_id+'" data-chat_id="'+getdata+'">
</form>
最佳答案
您必须在表单数据中传递值
$.each($('input[type=file]')[0].files, function(i, value){
formData.append('file['+i+']', value); // change this to value
});
我使用的示例代码
$.each($('#upload_screenshot')[0].files,function(key,input){
formData.append('upload_screenshot[]', input);
});