Drag drop probleem

Overzicht Reageren

Sponsored by: Vacatures door Monsterboard

Patric hoog

patric hoog

01/08/2024 11:00:10
Quote Anchor link
Goede dag allemaal,

Ik heb een probleem met mijn script dat JSON data verwerkt en ik kom er niet helemaal uit wat er misgaat. Ik hoop dat iemand hier mij kan helpen.

Alvast bedankt voor jullie hulp!


Afbeelding


Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
<?php
session_start();
if (!defined('********')) {
    define('********', true);
}


error_reporting(E_ALL);
ini_set('display_errors', 1);

include_once("********.php");

if(empty($picture_upload_style)){
    echo "<link rel=\"stylesheet\" href=\"https://www.********.nl/style.css\"> <!-- css version 1e -->";
}

function
encryptFile($source, $dest, $key) {
    if (is_null($key)) {
        throw new Exception('Encryption key is not set');
    }

    $key = substr(hash('sha256', $key, true), 0, 32);
    $iv = openssl_random_pseudo_bytes(16);
    $input = file_get_contents($source);
    $ciphertext = openssl_encrypt($input, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    file_put_contents($dest, $iv . $ciphertext);
}

function
json_response($success, $data = null, $error = null) {
    $response = ['success' => $success];
    if ($data !== null) {
        $response['data'] = $data;
    }

    if ($error !== null) {
        $response['error'] = $error;
    }

    echo json_encode($response);
    exit;
}


if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['image'])) {
    header('Content-Type: application/json');
    ob_start(); // Start output buffering
    try {
        if (!isset($_SESSION['email'], $_SESSION['session_id'])) {
            throw new Exception('Session not set');
        }


        $email = $_SESSION['email'];
        $session_id = $_SESSION['session_id'];

        $stmt = $dbcreat->prepare("SELECT * FROM members WHERE md5(email) = ? AND session_id = ?");
        if ($stmt === false) {
            throw new Exception("Connection error: " . $dbcreat->error);
        }


        $stmt->bind_param("ss", $email, $session_id);
        $stmt->execute();
        $result = $stmt->get_result();

        if (!$data = $result->fetch_assoc()) {
            session_destroy();
            throw new Exception('User not authenticated');
        }


        $userId = $data['id'];
        $uploadDir = 'user_upload/' . $userId . '/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0775, true);
        }


        $uploadedFiles = [];
        foreach ($_FILES['image']['name'] as $index => $name) {
            if ($_FILES['image']['error'][$index] != UPLOAD_ERR_OK) {
                throw new Exception('File upload error: ' . $_FILES['image']['error'][$index]);
            }


            $fileExtension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
            $fileSize = $_FILES['image']['size'][$index];
            $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];
            $maxFileSize = 5 * 1024 * 1024; // 5MB

            if (!in_array($fileExtension, $allowed_extensions)) {
                throw new Exception('Invalid file type');
            }


            if ($fileSize > $maxFileSize) {
                throw new Exception('File size exceeds limit');
            }


            $tmpFilePath = $_FILES['image']['tmp_name'][$index];
            $randomNumber = mt_rand(100000, 999999);
            while (file_exists($uploadDir . $randomNumber . '.' . $fileExtension)) {
                $randomNumber = mt_rand(100000, 999999);
            }


            $filePath = $uploadDir . $randomNumber . '.' . $fileExtension;
            if (!$encryption_key) {
                throw new Exception('Encryption key not found');
            }

            encryptFile($tmpFilePath, $filePath, $encryption_key);

            $stmt = $dbcreat->prepare("INSERT INTO images (userid, image_link, password, password_lock) VALUES (?, ?, ?, ?)");
            if (!$stmt) {
                throw new Exception('SQL prepare failed: ' . $dbcreat->error);
            }


            $password = null;
            $password_lock = 0;
            if (isset($_POST['password']) && !empty($_POST['password'])) {
                $password = password_hash($_POST['password'], PASSWORD_BCRYPT);
                $password_lock = 1;
            }


            $stmt->bind_param('issi', $userId, $filePath, $password, $password_lock);
            if (!$stmt->execute()) {
                throw new Exception($stmt->error);
            }

            $stmt->close();

            $uploadedFiles[] = $filePath;
        }

        ob_clean(); // Clear the buffer before sending JSON response
        json_response(true, ['files' => $uploadedFiles]);
    }
catch (Exception $e) {
        ob_clean(); // Clear the buffer in case of an error
        json_response(false, null, $e->getMessage());
    }
}
else {
    // Display upload form and gallery
    echo '<div class="content-box">
            <div id="drop-area">
                <form class="my-form" enctype="multipart/form-data">
                    <p>Upload multiple files with the file dialog or by dragging and dropping images onto the dashed region</p>
                    <input type="file" id="fileElem" name="image[]" multiple accept="image/*" onchange="handleFiles(this.files)">
                    <input type="password" id="filePassword" name="password" placeholder="Optional: Set a password for images">
                    <label class="button" for="fileElem">Select some files</label>
                </form>
                <progress id="progress-bar" max="100" value="0"></progress>
                <div id="gallery"></div>
            </div>'
;

    // Display uploaded images
    $userId = $data['id'] ?? 0; // Replace with appropriate session user ID
    if ($userId) {
        $stmt = $dbcreat->prepare("SELECT image_link FROM images WHERE userid = ?");
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $result = $stmt->get_result();

        echo '<div class="uploaded-images">';
        while ($row = $result->fetch_assoc()) {
            echo '<a href="' . $row['image_link'] . '" target="_blank">' . basename($row['image_link']) . '</a><br>';
        }

        echo '</div>';
    }


    echo '</div>';
}

?>



<script>
document.addEventListener('DOMContentLoaded', function() {
    let dropArea = document.getElementById('drop-area');

    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, preventDefaults, false);
        document.body.addEventListener(eventName, preventDefaults, false);
    });

    ['dragenter', 'dragover'].forEach(eventName => {
        dropArea.addEventListener(eventName, highlight, false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, unhighlight, false);
    });

    dropArea.addEventListener('drop', handleDrop, false);

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    function highlight(e) {
        dropArea.classList.add('highlight');
    }

    function unhighlight(e) {
        dropArea.classList.remove('highlight');
    }

    function handleDrop(e) {
        let dt = e.dataTransfer;
        let files = dt.files;
        handleFiles(files);
    }

    function handleFiles(files) {
        ([...files]).forEach(uploadFile);
    }

    function uploadFile(file) {
        let formData = new FormData();
        formData.append('image[]', file);

        let password = document.getElementById('filePassword').value;
        if (password) {
            formData.append('password', password);
        }

        fetch('', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            console.log('Upload result:', data);
            if (data.success) {
                alert("Upload successful!");
                displayUploadedFiles(data.data.files);
            } else {
                alert("Upload failed: " + data.error);
            }
        })
        .catch(error => {
            console.error('Upload error:', error);
            alert("Upload error: " + error.message);
        });
    }

    function displayUploadedFiles(files) {
        let gallery = document.getElementById('gallery');
        files.forEach(file => {
            let link = document.createElement('a');
            link.href = file;
            link.target = '_blank';
            link.textContent = file;
            gallery.appendChild(link);
            gallery.appendChild(document.createElement('br'));
        });
    }
});
</script>
Gewijzigd op 01/08/2024 11:04:30 door Patric hoog
 
PHP hulp

PHP hulp

23/11/2024 10:34:38
 
- Ariën  -
Beheerder

- Ariën -

01/08/2024 11:21:29
Quote Anchor link
Ik raad aan om eens in je developer-toolkit van je browser te kijken naar je JSON-request. Deze is blijkbaar verminkt, of geeft hele andere informatie (een error misschien) waarmee jouw script er weinig mee kan doen.
 
Carole Soto

Carole Soto

13/08/2024 08:46:38
Quote Anchor link
Hartelijk dank
 



Overzicht Reageren

 
 

Om de gebruiksvriendelijkheid van onze website en diensten te optimaliseren maken wij gebruik van cookies. Deze cookies gebruiken wij voor functionaliteiten, analytische gegevens en marketing doeleinden. U vindt meer informatie in onze privacy statement.