Ajax发送没有表单标签的文件并提交
我需要通过ajax发送图像,但不提交表单。通常,通过表单提交,我通过 $_FILES[ 'images' ][ 'tmp_name' ]; 获取图像 我尝试发送文件,但进入数组对象 FileList,但无法获取文件。我错了什么?
html
<div class="col-12 col-sm-6 pt-sm-3 formimgaj" enctype="multipart/form-data">
<div class="form-group">
<input type="file" name="images" accept="image/*" class="form-control-file">
<input class="btn btn-sm btn-success butt_img_upload" value="upload">
</div> </div>
js
$( '.formimgaj' ).each( function () {
var forminput = $( ".form-control-file", this );
$(this).find( ".butt_img_upload" ).on( 'click', function ( e ) {
e . preventDefault();
var form_data = new FormData();
form_data.append('images[]', forminput[0].files );
form_data.append('type', 'updateimg');
new Response(form_data).text().then(console.log)
$.ajax({
type: 'post',
url: 'php/update.php',
data: form_data,
processData: false,
contentType: false,
cache: false,
success: function ( data ) {
console.log(data);
}
})
})
});
日志
Array
(
[images] => Array
(
[0] => [object FileList]
)
[type] => updateimg
)
谢谢
i need send images by ajax, but without submit form. Normally, with form submit i get images by $_FILES[ 'images' ][ 'tmp_name' ];
i try to send files, but i get in array object FileList, and i can't get files. what i wrong?
html
<div class="col-12 col-sm-6 pt-sm-3 formimgaj" enctype="multipart/form-data">
<div class="form-group">
<input type="file" name="images" accept="image/*" class="form-control-file">
<input class="btn btn-sm btn-success butt_img_upload" value="upload">
</div> </div>
js
$( '.formimgaj' ).each( function () {
var forminput = $( ".form-control-file", this );
$(this).find( ".butt_img_upload" ).on( 'click', function ( e ) {
e . preventDefault();
var form_data = new FormData();
form_data.append('images[]', forminput[0].files );
form_data.append('type', 'updateimg');
new Response(form_data).text().then(console.log)
$.ajax({
type: 'post',
url: 'php/update.php',
data: form_data,
processData: false,
contentType: false,
cache: false,
success: function ( data ) {
console.log(data);
}
})
})
});
log
Array
(
[images] => Array
(
[0] => [object FileList]
)
[type] => updateimg
)
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要循环遍历
forminput[0].files
中的所有值,并将它们作为单独的项目添加到form_data
中。您不能将FileList
对象直接放入FormData
参数中,它会转换为字符串。You need to loop over all the values in
forminput[0].files
and add them as separate items inform_data
. You can't put theFileList
object directly into aFormData
parameter, it gets converted to a string.