Django ajax 图像上传和裁剪图像保存



我想使用 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',)

模板.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'})

我读到这个:https://simpleisbetterthancomplex.com/tutorial/2017/03/02/how-to-crop-images-in-a-django-application.html

现在我需要用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'

问题1:如何解决'MultiValueDict' object has no attribute 'read'

问题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 的图像非常新手,所以我需要您的解释或修改。

感谢您阅读可怜的问题。

我只能给你一个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)
}
});
});

最新更新