简体   繁体   中英

Upload of image doesn't work (dealing with cropper.js on a modal)

I have a modal in my signup.html that should display a image cropper, from cropper.js when a file is uploaded. But if I try to change the file I'm uploading, the modal shows up with the first file that I used. What am I doing wrong?

PS: Is the first time I'm using cropper.js.

Here is my code:

signup.html:

{% extends 'base.html' %}

{% load static %}

{% block content %}
<header>
    <img src="{% static 'img/logo-min.png' %}" alt="Logo-min">
</header>
<div class="card-signup">
    <form enctype="multipart/form-data" method="POST" class="post-form">
        <h1>+ Cadastro de novo aluno</h1>
        {% csrf_token %}
        {{ credentials_form }}
        {{ personal_info_form }}
        <button type="submit" class="save btn btn-default">Confirmar</button>
    </form>
</div>
<div id="modal">
    <div class="canvas">
        <a class="close">&times;</a>
        <img class="modal-content" id="image">
        <button class="crop">Cortar</button>
    </div>
</div>
{% endblock %}

image_cropper.js:

showModal = () => {
    let modal = document.querySelector('#modal');
    let image = document.querySelector('#image');

    let file = document.querySelector('input[type=file]').files[0];
    let fileReader = new FileReader();

    fileReader.onload = () => {
        modal.style.display = 'flex';
        image.src = fileReader.result;
        let cropper = new Cropper(image, {
            dragMode: 'move',
            aspectRatio: 1 / 1,
            autoCropArea: 0.65,
            restore: false,
            guides: false,
            center: false,
            highlight: false,
            cropBoxMovable: false,
            cropBoxResizable: false,
            toggleDragModeOnDblclick: false,
        });

        let crop_button = document.querySelector('.crop');
        crop_button.onclick = cropper.crop;
    }

    if (file) {
        fileReader.readAsDataURL(file);
    } else {
        image.src = '';
    }
}

closeModal = () => {
   let modal = document.querySelector('#modal');
   picture_input.value = '';
   modal.style.display = 'none';
}

let picture_input = document.querySelector('#id_picture');
picture_input.onchange = showModal;

let close_button = document.querySelector('.close');
close_button.onclick = closeModal;

The file input is rendered by Django, but it looks like this:

<input name="picture" accept="image/*" required="" id="id_picture" type="file">

To delete the instance of the image, you need to use the destroy() method available. In my code, I put it like this:

close_button.onclick = closeModal = () => {
    modal.style.display = 'none';
    cropper.destroy();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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