现在我有了这个图片上传表格:
image_upload.html
<form id="image_upload_form" enctype="multipart/form-data" method="post" action="">
<input id="id_image" type="file" name="image">
<input type="submit" value="Upload">
</form>
以下代码是我的Django forms.py和views.py来处理POST请求:
forms.py
class ImageUploadForm(forms.Form):
image = forms.ImageField()
views.py
class MyView(DetailView):
def post(self, request, *args, **kwargs):
form = ImageUploadForm(request.POST, request.FILES)
if form.is_valid():
print("FORM IS VALID!!!");
# Do Something....
上传图像文件并提交表单后,数据会正确地发布到服务器上,我收到回复“FORM IS VALID !!!”。
但是,我想添加一个拖放上传功能,所以我添加了这段代码:
image_upload.html
<form id="image_upload_form" enctype="multipart/form-data" method="post" action="">
<input id="id_image" type="file" name="image">
<input type="submit" value="Upload">
</form>
<div id="image_upload_drop_area">Drop Image Here</div>
upload.js
var drop_area = $("#image_upload_drop_area");
drop_area.bind('drop', drop);
function drop(event) {
var file = event.originalEvent.dataTransfer.files [0];
data = new FormData();
data.append('image', file);
$.ajax({
url: location.href,
data: data,
processData: false,
type: 'POST',
success: function ( data ) {
console.log("SENT SUCCESS");
}
});
这不起作用。 “数据”肯定会发送到服务器(我从服务器获得“SENT SUCCESS”消息),但不作为我的“#image_upload_form”的输入。
换句话说,我没有得到“表格有效!!!”消息,意味着它没有存储在“request.FILES。”中。
我应该如何更改javascript代码,以便将图像文件作为(“#imag_upload_form”)的表单数据发送? (即id为“#id_image”的输入)
由于