javascript - 如何在formdata上附加多个文件输入
问题描述
我必须使用表单数据发送多个文件,但我的代码不起作用,谁能告诉我哪里出错了。
$('#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);
});
推荐阅读
- c - 如何在不使用倒带功能的情况下清除输入缓冲区?
- hibernate - 休眠查询命名参数中的单引号给出错误
- java - Stripe Android - 设置意图后将卡附加到客户
- r - 根据 R / ggraph 中的 'y' 值垂直组织图节点
- python - 如何更改字符串中的特定字符?
- java - 无法在 child() 中为参数“pathString”传递 null 如何解决此错误
- php - 如何在 php + mysql 更新之前检查重复条目?
- r - 如何使用 R 的 summarytools 包中的 ctable 重命名行和列变量名称输出?
- c - 使用c中的指针解码传递给函数的2个元素数组
- python - 接受后存储好友请求(在数据库中)