django中模板页实现文件上传和前端验证

2024年4月23日 18:57 by wst

django

功能

实现文件上传以及相关字段提交,使用的fromData结构。

实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Upload</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
        // Function to get CSRF token from cookies
        function getCSRFToken() {
            var cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = cookies[i].trim();
                    // Check if the cookie name is csrftoken
                    if (cookie.substring(0, 10) === 'csrftoken=') {
                        // Get the csrf token value
                        cookieValue = decodeURIComponent(cookie.substring(10));
                        break;
                    }
                }
            }
            return cookieValue;
        }

        // Function to handle form submission
        function submitForm(event) {
            event.preventDefault();

            var form = document.getElementById('uploadForm');
            var formData = new FormData(form);

            axios.post('/image_processor/change-background/', formData, {
                headers: {
                    'X-CSRFToken': getCSRFToken()
                }
            })
            .then(function(response) {
                var resultDiv = document.getElementById('result');
                var img = document.createElement('img');
                img.src = 'data:image/png;base64,' + response.data.image;
                resultDiv.appendChild(img);
            })
            .catch(function(error) {
                alert('An error occurred: ' + error.response.data.error);
            });
        }
    </script>
</head>
<body>
    <form id="uploadForm" enctype="multipart/form-data" onsubmit="submitForm(event)">
        {% csrf_token %}
        <input type="file" name="image" id="imageInput" accept="image/*">
        <button type="submit">Upload</button>
    </form>
    <div id="result"></div>
</body>
</html>

注释

功能要点:

1. 加载csrf token 到页面中;

2. 验证表单的所有字段是否都填了(特别是文件选择);

3. 通过axios提交数据,并动态的把图片填充到div中;


Comments(0) Add Your Comment

Not Comment!