我想用ajax上传图片,裁剪上传的图片并保存图片。
我使用枕头5.1.0。,django 2.0.5。
models.py:
class TestPhoto(models.Model):
file = models.ImageField()
forms.py:
class TestPhotoFrom(forms.ModelForm):
# this is not necessary part, you can ignore it.
x = forms.FloatField(widget=forms.HiddenInput())
y = forms.FloatField(widget=forms.HiddenInput())
class Meta:
model = TestPhoto
fields = ('file', 'x', 'y',)
template.html:
<form method="post" enctype="multipart/form-data" id="formUpload">
{% csrf_token %}
{{ form }}
</form>
<button class="js-crop-and-upload">button</button>
<script>
$(function () {
$(".js-crop-and-upload").click(function () {
//Get file from form.
var form_upload = $("#formUpload")[0];
var form_data = new FormData(form_upload);
//Send file with ajax.
$.ajax({
url:'/crop/',
type:'post',
dataType:'json',
cache:false,
processData: false,
contentType: false,
data:{
'file': form_data,
'value': 'test_value',
},
success:function (data) {
console.log(data)
}
});
});
});
</script>
views.py:
def crop(request):
if request.method == "GET":
form = TestPhotoFrom()
return render(request, 'authapp/crop.html', {'form': form})
else:
if request.is_ajax():
# get file from request.
file = request.FILES
image = Image.open(file)
# cropping image
cropped_image = image.crop((0, 0, 200, 200))
resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS)
# save cropped image
resized_image.save()
return JsonResponse({'success': 'file_uploaded'})
现在我需要用jquery-ajax做到这一点。
但是当我单击按钮执行ajax请求时,服务器控制台正在打印此错误:
'MultiValueDict' object has no attribute 'read'
我该怎么做?
抱歉,我不知道views.py
上的这些部分是否正确:
image = Image.open(file)
cropped_image = image.crop((0, 0, 200, 200))
resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS)
resized_image.save()
但在检查之前,我无法解决这个问题:'MultiValueDict' object has no attribute 'read'
Question.1:
我该如何解决'MultiValueDict' object has no attribute 'read'
?
Question.2: 这部分是否正确?还是会运作良好?
image = Image.open(file)
cropped_image = image.crop((0, 0, 200, 200))
resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS)
resized_image.save()
因为我非常喜欢用django上的ajax上传图片,我想要你的解释或修改。
感谢您阅读不好的问题。
答案 0 :(得分:1)
我只能给你ajax方面的答案
使用FormData时,必须将其作为数据参数传递
如果您想添加其他字段,请使用append()
#formUpload
将是用于选择图像的文件输入的表单。
$(".js-crop-and-upload").click(function () {
//Get file from form.
var form_upload = $("#formUpload")[0];
var form_data = new FormData(form_upload);
form_data.append('value', 'test_value');
//Send file with ajax.
$.ajax({
url:'/crop/',
type:'post',
dataType:'json',
cache:false,
processData: false,
contentType: false,
data:form_data,
success:function (data) {
console.log(data)
}
});
});