Browse Source

Allow file upload

keplyx 1 year ago
parent
commit
3b50449d56

+ 7
- 0
admin/form_ajax.php View File

@@ -0,0 +1,7 @@
1
+<?php
2
+$relativePath = "../";
3
+require_once $relativePath.'classes/postHandler.php';
4
+
5
+$handler = new PostHandler($_POST, $_FILES);
6
+
7
+echo json_encode($handler->do_action());

admin/save_manager.php → admin/json_ajax.php View File


+ 8
- 0
assets/css/categories.css View File

@@ -40,10 +40,13 @@
40 40
 .list-name {
41 41
     font-weight: bold;
42 42
     width: 150px;
43
+    height: 50px;
44
+    overflow: hidden;
43 45
 }
44 46
 
45 47
 .list-description {
46 48
     width: 200px;
49
+    height: 50px;
47 50
     overflow: hidden;
48 51
 }
49 52
 
@@ -57,3 +60,8 @@
57 60
     width: 200px;
58 61
     text-align: right;
59 62
 }
63
+
64
+.list-image img  {
65
+    width: 50px;
66
+    height: 50px;
67
+}

+ 24
- 3
assets/js/ajaxManager.js View File

@@ -15,7 +15,7 @@ class AjaxManager {
15 15
         };
16 16
         let response = await $.ajax({
17 17
             type: "POST",
18
-            url: "save_manager.php",
18
+            url: "json_ajax.php",
19 19
             data: JSON.stringify(data),
20 20
             dataType: "json",
21 21
             contentType: "application/json; charset=utf-8",
@@ -32,7 +32,7 @@ class AjaxManager {
32 32
         };
33 33
         let response = await $.ajax({
34 34
             type: "POST",
35
-            url: "save_manager.php",
35
+            url: "json_ajax.php",
36 36
             data: JSON.stringify(data),
37 37
             dataType: "json",
38 38
             contentType: "application/json; charset=utf-8",
@@ -49,7 +49,7 @@ class AjaxManager {
49 49
         };
50 50
         let response = await $.ajax({
51 51
             type: "POST",
52
-            url: "save_manager.php",
52
+            url: "json_ajax.php",
53 53
             data: JSON.stringify(formattedData),
54 54
             dataType: "json",
55 55
             contentType: "application/json; charset=utf-8",
@@ -57,6 +57,27 @@ class AjaxManager {
57 57
         console.log(response);
58 58
         return response['data'];
59 59
     }
60
+
61
+    static async saveArticleImage(image, id) {
62
+        if (image !== undefined) {
63
+            let formData = new FormData();
64
+            formData.append('type', 'image');
65
+            formData.append('data', id);
66
+            formData.append('image', image);
67
+            let response = await $.ajax({
68
+                type: "POST",
69
+                url: "form_ajax.php",
70
+                data: formData,
71
+                cache: false,
72
+                contentType: false,
73
+                processData: false,
74
+            });
75
+            response = JSON.parse(response);
76
+            console.log(response);
77
+            return response['status'];
78
+        } else
79
+            return 1;
80
+    }
60 81
 }
61 82
 
62 83
 

+ 5
- 0
assets/js/articles.js View File

@@ -4,6 +4,11 @@ $(document).ready(function () {
4 4
     listManager = new ListManager($("#dataList"), 'article',
5 5
         [
6 6
             {
7
+                name: 'image',
8
+                description: 'Image',
9
+                type: 'image'
10
+            },
11
+            {
7 12
                 name: 'name',
8 13
                 description: 'Nom',
9 14
                 type: 'text'

+ 37
- 15
assets/js/listManager.js View File

@@ -84,6 +84,8 @@ class ListManager {
84 84
                 listItem += "<i class='mdi mdi-" + item["icon"] + "' style='margin-right: 5px'></i></span>";
85 85
             else if (this.editableTypes[i]["type"] === 'checkboxes') {
86 86
                 listItem += this.getCategoryIcons(item['id']);
87
+            } else if (this.editableTypes[i]["type"] === 'image') {
88
+                listItem += '<img src="../uploaded_images/' + item['id'] + '.jpg" /></span>'
87 89
             } else
88 90
                 listItem += item[this.editableTypes[i]["name"]] + '</span>';
89 91
         }
@@ -113,25 +115,43 @@ class ListManager {
113 115
     }
114 116
 
115 117
     getFormData(defaultValues) {
116
-        let formData = '<form action="" class="categoryForm"><div class="form-group">';
118
+        let formData = '<form id="popupForm" name="popupForm" method="post" enctype="multipart/form-data"><div class="form-group">';
117 119
         for (let i = 0; i < this.editableTypes.length; i++) {
118 120
             let inputId = this.editableTypes[i]['name'] + 'Input';
121
+            let inputName = this.editableTypes[i]['name'];
119 122
             let inputType = this.editableTypes[i]['type'] === 'number' ? 'number' : 'text';
120 123
             let value = defaultValues[this.editableTypes[i]['name']] !== undefined ? defaultValues[this.editableTypes[i]['name']] : '';
121 124
             let icon = '';
122 125
             formData += '<label for="' + inputId + '">' + this.editableTypes[i]['description'] + ' :</label>';
123
-            if (this.editableTypes[i]['type'] !== 'checkboxes') {
126
+            if (this.editableTypes[i]['type'] === 'image') {
127
+                formData += this.getImagePicker(defaultValues['id']);
128
+            } else if (this.editableTypes[i]['type'] === 'checkboxes') {
129
+                formData += this.getCategoryCheckboxes(defaultValues['id']);
130
+            } else {
124 131
                 if (this.editableTypes[i]['name'] === 'icon')
125 132
                     formData += "<i class='mdi mdi-" + value + "' style='margin-left: 5px'></i>";
126
-                formData += '<input id="' + inputId + '" type="' + inputType + '" placeholder="Entrez une valeur" class="form-control" value="' + value + '" required />';
127
-            } else {
128
-                formData += this.getCategoryCheckboxes(defaultValues['id']);
133
+                formData += '<input name="' + inputName + '" id="' + inputId + '" type="' + inputType + '" placeholder="Entrez une valeur" class="form-control" value="' + value + '" required />';
134
+
129 135
             }
130 136
         }
131 137
         formData += "</div></form>";
132 138
         return formData;
133 139
     }
134 140
 
141
+    getImagePicker(id) {
142
+        return (
143
+            '<img style="width: 50px; height: 50px" src="../uploaded_images/' + id + '.jpg" id="image_' + id + '"/>' +
144
+            '<div class="custom-file">\n' +
145
+            '<input ' +
146
+            'type="file" ' +
147
+            'class="custom-file-input" ' +
148
+            'id="fileInput"' +
149
+            'accept="image/jpeg"' +
150
+            '>\n' +
151
+            '<label class="custom-file-label" for="customFile">Choose file</label>\n' +
152
+            '</div>');
153
+    }
154
+
135 155
     getFormValues(form) {
136 156
         let values = [];
137 157
         for (let i = 0; i < this.editableTypes.length; i++) {
@@ -181,7 +201,7 @@ class ListManager {
181 201
 
182 202
     updateListItemCategories(categories, index) {
183 203
         if (index === -1)
184
-            index = this.displayedData.length -1;
204
+            index = this.displayedData.length - 1;
185 205
         let iconContainer = this.displayedData[index].find(".list-category");
186 206
         for (let i = 0; i < categories.length; i++) {
187 207
             iconContainer.html(this.getCategoryIcons(this.currentData[index]['id']));
@@ -201,6 +221,10 @@ class ListManager {
201 221
         this.associationTable = newTable;
202 222
     }
203 223
 
224
+    updateArticleImage(image, index) {
225
+        $(this.displayedData[index].find("img")[0]).attr('src', window.URL.createObjectURL(image));
226
+    }
227
+
204 228
     showEditPopup(index) {
205 229
         let defaultValues = {};
206 230
         let title = "Créer une nouvelle entrée";
@@ -218,6 +242,10 @@ class ListManager {
218 242
                     text: 'Sauvegarder',
219 243
                     btnClass: 'btn-blue',
220 244
                     action: async function () {
245
+                        let image = undefined;
246
+                        if (this.$content.find('input[type=file]').length > 0)
247
+                            image = this.$content.find('input[type=file]')[0].files[0];
248
+
221 249
                         let values = thisInstance.getFormValues(this.$content);
222 250
 
223 251
                         if (!thisInstance.isFormValid(values)) {
@@ -253,6 +281,9 @@ class ListManager {
253 281
                             if (result) {
254 282
                                 thisInstance.updateAssociationList(id, categories);
255 283
                                 thisInstance.updateListItemCategories(categories, index);
284
+                                let imageResult = await AjaxManager.saveArticleImage(image, id);
285
+                                if (imageResult === 0)
286
+                                    thisInstance.updateArticleImage(image, index);
256 287
                             }
257 288
                         }
258 289
                     }
@@ -268,15 +299,6 @@ class ListManager {
268 299
                 cancelButton: {
269 300
                     text: 'Annuler',
270 301
                 },
271
-            },
272
-            onContentReady: function () {
273
-                // bind to events
274
-                let jc = this;
275
-                this.$content.find('form').on('submit', function (e) {
276
-                    // if the user submits the form by pressing enter in the field.
277
-                    e.preventDefault();
278
-                    jc.$$formSubmit.trigger('click'); // reference the button and click it
279
-                });
280 302
             }
281 303
         });
282 304
     }

+ 0
- 219
assets/js/stock.js View File

@@ -1,219 +0,0 @@
1
-let currentDataset = [];
2
-let currentTypes = [];
3
-
4
-function initValuesFromPHPDump() {
5
-    currentDataset = json_dump.articles; // json_dump is set using PHP
6
-    currentTypes = json_dump.types;
7
-    console.log(currentDataset);
8
-    console.log(currentTypes);
9
-    generateTable(currentDataset);
10
-}
11
-
12
-
13
-
14
-$(document).ready(function () {
15
-    if (json_dump !== undefined) {
16
-        initValuesFromPHPDump();
17
-        generateTypeCheckboxes();
18
-    }
19
-    setEditFieldValues('', '', '', '', '', '', '');
20
-});
21
-
22
-
23
-function generateTable(dataset) {
24
-    for (let i = 0; i < dataset.length; i++) {
25
-        generateLine(dataset[i]);
26
-    }
27
-}
28
-
29
-function generateLine(item) {
30
-    $.selector_cache('#stockTable').append(
31
-        '<tr id="row_' + item.code + '">' +
32
-        '<td>' + item.name + '</td>' +
33
-        '<td>' + item.description + '</td>' +
34
-        '<td>' + item.quantity + '</td>' +
35
-        '<td>' + item.price + '</td>' +
36
-        '<td>' + item.code + '</td>' +
37
-        '<td><span id="typeList_' + item.code + '"></span></td>' +
38
-        '<td><a href="' + item.image + '" target="_blank"><img class="row-img" src="' + item.image + '"/></a></td>' +
39
-        '<td>' +
40
-        '<button class="btn btn-danger" id="delete_' + item.code + '" onclick="deleteItem(this)"><i class="fas fa-times"></i></button>' +
41
-        '<button class="btn btn-primary" id="edit_' + item.code + '" onclick="editItem(this)"><i class="fas fa-edit"></i></button>' +
42
-        '</td>' +
43
-        '</tr>'
44
-    );
45
-    // Fill in the type cell
46
-    for (let i = 0; i < item.type.length; i++) {
47
-        let type = getTypeOfId(item.type[i]);
48
-        $('#typeList_' + item.code).append(
49
-            '<span class="mdi mdi-' + type.icon + '"></span>'
50
-        );
51
-    }
52
-}
53
-
54
-function generateTypeCheckboxes() {
55
-    for (let i = 0; i < currentTypes.length; i++) {
56
-        let id = 'typeCheck_' + currentTypes[i].id;
57
-        $('#typeCheckboxesCell').append(
58
-            '<div class="form-check">' +
59
-            '<input type="checkbox" class="form-check-input" id="' + id + '">' +
60
-            '<label class="form-check-label" for="' + id + '">' +
61
-            '<span class="mdi mdi-' + currentTypes[i].icon + '"></span>' + currentTypes[i].name + '</label>' +
62
-            '</div>'
63
-        );
64
-    }
65
-}
66
-
67
-function getTypeOfId(id) {
68
-    let item = {};
69
-    for (let i = 0; i < currentTypes.length; i++) {
70
-        if (currentTypes[i].id === id) {
71
-            item = currentTypes[i];
72
-            break;
73
-        }
74
-    }
75
-    return item;
76
-}
77
-
78
-function getItemOfCode(code) {
79
-    let item = {};
80
-    for (let i = 0; i < currentDataset.length; i++) {
81
-        if (currentDataset[i].code === code) {
82
-            item = currentDataset[i];
83
-            break;
84
-        }
85
-    }
86
-    return item;
87
-}
88
-
89
-function addNewItem() {
90
-    if (isItemInputFilled()) {
91
-        let item = {
92
-            name: sanitizeString($.selector_cache('#nameInput').val()),
93
-            description: sanitizeString($.selector_cache('#descriptionInput').val()),
94
-            quantity: sanitizeNumber($.selector_cache('#quantityInput').val()),
95
-            price: sanitizeNumber($.selector_cache('#priceInput').val()),
96
-            code: $.selector_cache('#codeInput').val(),
97
-            type: getTypesChecked(),
98
-            image: $.selector_cache('#imageInput').val(),
99
-        };
100
-        if (isCodeAvailable(item.code)) {
101
-            setEditFieldValues('', '', '', '', [], '', '');
102
-            currentDataset.push(item);
103
-            generateLine(item);
104
-        }
105
-    }
106
-}
107
-
108
-function editItem(elem) {
109
-    if (isItemInputEmpty()) {
110
-        let code = elem.id.replace('edit_', '');
111
-        let item = getItemOfCode(code);
112
-        setEditFieldValues(item.name, item.description, item.quantity, item.price, item.code, item.type, item.image);
113
-        removeItemFromList(item); // Move the item in the edit fields
114
-    }
115
-}
116
-
117
-function deleteItem(elem) {
118
-    let code = elem.id.replace('delete_', '');
119
-    let item = getItemOfCode(code);
120
-    removeItemFromList(item);
121
-}
122
-
123
-function removeItemFromList(item) {
124
-    currentDataset.splice(currentDataset.indexOf(item), 1);
125
-    $('#row_' + item.code).remove();
126
-}
127
-
128
-function getTypesChecked() {
129
-    let types = [];
130
-    for (let i = 0; i < currentTypes.length; i++) {
131
-        let id = 'typeCheck_' + currentTypes[i].id;
132
-        if ($('#' + id).is(':checked')) {
133
-            types.push(currentTypes[i].id);
134
-        }
135
-    }
136
-    return types;
137
-}
138
-
139
-function setTypesChecked(types) {
140
-    for (let i = 0; i < currentTypes.length; i++) {
141
-        let id = 'typeCheck_' + currentTypes[i].id;
142
-        $('#' + id).prop('checked', types.indexOf(currentTypes[i].id) !== -1);
143
-    }
144
-    return types;
145
-}
146
-
147
-function setEditFieldValues(name, description, quantity, price, code, type, image) {
148
-    $.selector_cache('#nameInput').val(name);
149
-    $.selector_cache('#descriptionInput').val(description);
150
-    $.selector_cache('#quantityInput').val(quantity);
151
-    $.selector_cache('#priceInput').val(price);
152
-    $.selector_cache('#codeInput').val(code);
153
-    $.selector_cache('#codeInput').val(code);
154
-    setTypesChecked(type);
155
-    $.selector_cache('#imageInput').val(image);
156
-}
157
-
158
-function isCodeAvailable (code) {
159
-    let isAvailable = true;
160
-    for (let i = 0; i < currentDataset.length; i++) {
161
-        if (currentDataset[i].code === code) {
162
-            isAvailable = false;
163
-            break;
164
-        }
165
-    }
166
-    return isAvailable;
167
-}
168
-
169
-function isItemInputEmpty() {
170
-    return $.selector_cache('#nameInput').val() === '' &&
171
-        $.selector_cache('#descriptionInput').val() === '' &&
172
-        $.selector_cache('#quantityInput').val() === '' &&
173
-        $.selector_cache('#priceInput').val() === '' &&
174
-        $.selector_cache('#codeInput').val() === '' &&
175
-        $.selector_cache('#imageInput').val() === '' &&
176
-        getTypesChecked().length === 0;
177
-}
178
-
179
-function isItemInputFilled() {
180
-    return $.selector_cache('#nameInput').val() !== '' &&
181
-        $.selector_cache('#descriptionInput').val() !== '' &&
182
-        $.selector_cache('#quantityInput').val() !== '' &&
183
-        $.selector_cache('#priceInput').val() !== '' &&
184
-        $.selector_cache('#codeInput').val() !== '' &&
185
-        $.selector_cache('#imageInput').val() !== '' &&
186
-        getTypesChecked().length > 0;
187
-}
188
-
189
-
190
-
191
-function saveDataset() {
192
-    AjaxManager.saveData(currentTypes, currentDataset);
193
-}
194
-
195
-function sanitizeString(str) {
196
-    return str.trim();
197
-}
198
-
199
-function sanitizeNumber(nbrStr) {
200
-    return nbrStr.replace(/\s/g,'');
201
-}
202
-
203
-function scanArticle(code) {
204
-    let data = {
205
-        password: 'coucou',
206
-        code : code,
207
-    };
208
-    $.ajax({
209
-        type: "POST",
210
-        url: "../ajax/scan_article.php",
211
-        data: JSON.stringify(data),
212
-        dataType: "json",
213
-        contentType: "application/json; charset=utf-8",
214
-        complete: function (data) {
215
-            // alert(data.responseText);
216
-            console.log(data.responseText);
217
-        },
218
-    });
219
-}

+ 29
- 3
classes/postHandler.php View File

@@ -3,7 +3,7 @@ require_once 'dao.php';
3 3
 
4 4
 class PostHandler
5 5
 {
6
-    private $valid_types = ["article", "category", "article_categories"];
6
+    private $valid_types = ["article", "category", "article_categories", 'image'];
7 7
     private $valid_actions = ["create", "update", "remove", "get"];
8 8
 
9 9
     private $action;
@@ -12,7 +12,7 @@ class PostHandler
12 12
     private $filesData;
13 13
     private $data;
14 14
     private $dao;
15
-    private $uploadBaseDir = '../../uploaded_images/';
15
+    private $uploadBaseDir = '../uploaded_images/';
16 16
 
17 17
     private $responseArray = array(
18 18
         "status" => 0,
@@ -33,7 +33,9 @@ class PostHandler
33 33
     public function do_action()
34 34
     {
35 35
         $result = -1;
36
-        if (count($this->data) > 0) {
36
+        if ($this->type == "image") {
37
+            $result = $this->save_image();
38
+        } else if (count($this->data) > 0) {
37 39
             if ($this->action == "create")
38 40
                 $result = $this->create();
39 41
             else if ($this->action == "update")
@@ -55,6 +57,30 @@ class PostHandler
55 57
         return $this->responseArray;
56 58
     }
57 59
 
60
+    private function save_image()
61
+    {
62
+        $success = true;
63
+        if ($this->filesData["image"]["size"] > 0 && $this->data != null) {
64
+            $uploadPath = $this->uploadBaseDir.$this->data.".jpg";
65
+
66
+            if (move_uploaded_file($this->filesData["image"]["tmp_name"], $uploadPath)) {
67
+                $this->responseArray["message"] = "Image upload success";
68
+            } else {
69
+                $this->responseArray["message"] = "Image upload failure: ". $uploadPath;
70
+                $this->responseArray["status"] = 1;
71
+                $success = false;
72
+            }
73
+        } else {
74
+            $this->responseArray["message"] = "No valid file to send";
75
+            $this->responseArray["status"] = 1;
76
+            $success = false;
77
+        }
78
+        if ($success)
79
+            return 0;
80
+        else
81
+            return json_encode($this->filesData)."id: ".$this->data;
82
+    }
83
+
58 84
     function create()
59 85
     {
60 86
         $result = -1;

Loading…
Cancel
Save