简体   繁体   English

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

[英]Django ajax image upload and cropped image saving

I want to upload image with ajax, crop the uploaded image and save the image.我想用ajax上传图片,裁剪上传的图片并保存图片。

I uses pillow 5.1.0., django 2.0.5.我使用枕头 5.1.0.,django 2.0.5。

models.py:模型.py:

class TestPhoto(models.Model):
    file = models.ImageField()

forms.py:表格.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:模板.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:视图.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'})

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

And now I need to do that with jquery-ajax.现在我需要用 jquery-ajax 来做到这一点。

But when I click button to do ajax request, server console is printing this error: 'MultiValueDict' object has no attribute 'read'但是当我单击按钮执行 ajax 请求时,服务器控制台正在打印此错误: 'MultiValueDict' object has no attribute 'read'

How can I do that?我怎样才能做到这一点?

Sorry, I don't know also whether these part on views.py is correct or not:抱歉,我也不知道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()

But before checking it, I cannot solve this: 'MultiValueDict' object has no attribute 'read'但在检查之前,我无法解决这个问题: 'MultiValueDict' object has no attribute 'read'

Question.1: How can I solve 'MultiValueDict' object has no attribute 'read' ?问题 1:如何解决'MultiValueDict' object has no attribute 'read'

Question.2: Is this part correct?问题2:这部分正确吗? Or will it be working well?或者它会运作良好?

image = Image.open(file)
cropped_image = image.crop((0, 0, 200, 200))
resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS)
resized_image.save()

Because I'm very newbie in uploading image with ajax on django very little, I want your explanation or modification.因为我在 django 上用ajax上传图片非常新手,我想要你的解释或修改。

Thanks for reading poor question.感谢您阅读糟糕的问题。

I can only give you an answer for the ajax side我只能给你ajax方面的答案
When using FormData, you have to pass it as the data parameter.使用 FormData 时,必须将其作为数据参数传递。
If you want to add other fields you will use append()如果您想添加其他字段,您将使用append()
#formUpload would be the form with the file input used to select the image. #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)
        }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM