通过AJAX发送图像文件.request.FILES为空? [英] Sending image file via AJAX. request.FILES is empty?
问题描述
我正在尝试使用Ajax发送图像数据.但是我在后端得到的 request.FILES
是空的.我已经在表单中添加了 multipart/form-data
,方法是 POST
.
I am trying to send image data using Ajax. But request.FILES
that I get at the backend is empty. I have added multipart/form-data
to my form and the method is POST
.
这是我的AJAX通话:
here is my AJAX call:
$(document).on('submit', '#profile_edit_form', function(event){
event.preventDefault();
$.ajax({
url : "/users/update_profile_info/",
type : 'post',
dataType: 'json',
data : $(this).serialize(),
success : function(data) {
$('#profile_name_tag').html(data.username);
$('#username_navbar').html(data.username);
//SENDING THE IMAGE VIA AJAX HERE
var img_data = $('#id_image').get(0).files;
formdata = new FormData();
formdata.append("img_data", img_data);
$.ajax({
url : "/users/update_profile_image/",
type : 'POST',
enctype : "multipart/form-data",
data : formdata,
cache : false,
contentType : false,
processData : false,
success : function(data) {
console.log('success');
//$('#profile_picture').html(data.)
},
error: function(data) {
console.log('fail');
}
});
},
error: function(data) {
console.log('fail');
}
});
});
这是我的表格:
<form id="profile_edit_form" method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb4"> Profile Info </legend>
{{u_form|crispy}}
{{p_form|crispy}}
</fieldset>
<button class="btn btn-outline-info" type="submit"> Update Info </button>
</form>
如您所见,我使用的是顺式表格.图片字段位于 p_form
As you can see I am using cispy forms. the image field is inside the p_form
这是我的 django视图
@login_required
def update_profile_image(request):
print(not request.FILES)
if request.method == 'POST':
p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user)
if p_form.is_valid():
p_form.save()
context = {'None': 'none'}
return JsonResponse(context)
else:
return HttpResponse('None')
打印(不是request.FILES)
返回True,并且图像当然没有上载.
print(not request.FILES)
returns True and the image is of course not uploaded.
我检查了很多类似的问题.但所有这些解决方案都是在我已经完成的表单中添加 multipart/form-data
.那么问题出在哪里呢?
I have checked so many similar questions. but in all of them the solution was adding multipart/form-data
to the form which I have already done.
So any ideas where the problem is?
谢谢!
推荐答案
我将代码更改为
var img_data = $('#id_image').get(0).files[0];
formdata = new FormData();
formdata.append("img_data", img_data);
//console.log(formdata.get("img_data"));
$.ajax({
url : "/users/update_profile_image/",
type : 'POST',
//enctype : "multipart/form-data", //it is done inside jquery
data : formdata,
cache : false,
contentType : false,
processData : false,
success : function(data) {
console.log('success');
//$('#profile_picture').html(data.)
},
error: function(data) {
console.log('image-fail');
}
});
它终于奏效了!
这篇关于通过AJAX发送图像文件.request.FILES为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!