datasync-blob 1.1.24 → 1.1.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,6 +6,8 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.DsBlob = void 0;
7
7
  var _react = _interopRequireWildcard(require("react"));
8
8
  var _propTypes = _interopRequireDefault(require("prop-types"));
9
+ var _reactToastify = require("react-toastify");
10
+ require("react-toastify/dist/ReactToastify.css");
9
11
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
10
12
  function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
11
13
  class DsBlob extends _react.Component {
@@ -20,11 +22,138 @@ class DsBlob extends _react.Component {
20
22
  this.debugging = false;
21
23
  }
22
24
 
25
+ //-----------------------------------------
26
+ /**
27
+ * PROTOTYPE : uploadToDatasyncCloud
28
+ * Purpose : Upload binary data to My Custom Cloud server using Datasync SncPushCloud endpoint and return the accessible URL for the uploaded file.
29
+ * @param base64Data
30
+ * @param fileName
31
+ */
32
+ uploadToDatasyncCloud = async pictureBlob => {
33
+ try {
34
+ const formData = new FormData();
35
+ let cloud_filename = pictureBlob.cloud_url_prefix.split('/').pop(); // Extract filename from cloud_url_prefix
36
+
37
+ console.log("Uploading to Datasync Cloud with filename:", cloud_filename);
38
+ formData.append('action', "syncPushCloud");
39
+ //formData.append('filename', `${CGUID()}.jpg`);
40
+ formData.append('filename', cloud_filename); // Extract filename from cloud_url_prefix
41
+
42
+ // Convert blob URL to actual binary data
43
+ let binaryString;
44
+ if (pictureBlob.isBlobUrl && pictureBlob.data.startsWith('blob:')) {
45
+ // Fetch the blob URL to get actual file content
46
+ console.log('Fetching blob URL:', pictureBlob.data);
47
+ const blobResponse = await fetch(pictureBlob.data);
48
+ const blob = await blobResponse.blob();
49
+
50
+ // Convert blob to ArrayBuffer then to Uint8Array
51
+ const arrayBuffer = await blob.arrayBuffer(); // Raw binary JPEG data
52
+ const uint8Array = new Uint8Array(arrayBuffer); // ← THIS CONTAINS THE GENUINE JPEG FILE BINARY DATA
53
+
54
+ // Convert to base64 string for transmission (chunked to avoid stack overflow)
55
+ let binaryStr = '';
56
+ const chunkSize = 8192; // Process in 8KB chunks to avoid stack overflow
57
+ for (let i = 0; i < uint8Array.length; i += chunkSize) {
58
+ const chunk = uint8Array.slice(i, i + chunkSize);
59
+ binaryStr += String.fromCharCode(...chunk);
60
+ }
61
+ binaryString = btoa(binaryStr); // ← THIS CONTAINS THE GENUINE JPEG FILE AS BASE64 STRING
62
+
63
+ console.log('Converted blob URL to binary data, size:', uint8Array.length);
64
+ } else if (Array.isArray(pictureBlob.binaryData)) {
65
+ // Convert Uint8Array or regular array to base64 string
66
+ const uint8Array = new Uint8Array(pictureBlob.binaryData);
67
+ let binaryStr = '';
68
+ const chunkSize = 8192;
69
+ for (let i = 0; i < uint8Array.length; i += chunkSize) {
70
+ const chunk = uint8Array.slice(i, i + chunkSize);
71
+ binaryStr += String.fromCharCode(...chunk);
72
+ }
73
+ binaryString = btoa(binaryStr);
74
+ } else if (pictureBlob.binaryData instanceof Uint8Array) {
75
+ // Already a Uint8Array, convert to base64
76
+ let binaryStr = '';
77
+ const chunkSize = 8192;
78
+ for (let i = 0; i < pictureBlob.binaryData.length; i += chunkSize) {
79
+ const chunk = pictureBlob.binaryData.slice(i, i + chunkSize);
80
+ binaryStr += String.fromCharCode(...chunk);
81
+ }
82
+ binaryString = btoa(binaryStr);
83
+ } else {
84
+ // Assume it's already a string
85
+ binaryString = pictureBlob.binaryData || "";
86
+ }
87
+ formData.append('binary', binaryString);
88
+ console.log("binaryString ->", binaryString.substring(0, 100) + '...'); // Log the beginning of the base64 string for debugging
89
+
90
+ const results = await fetch('http://localhost:8888/datasync-service/Sync.php', {
91
+ method: 'POST',
92
+ body: formData
93
+ });
94
+ if (!results.ok) {
95
+ throw new Error(`HTTP error! status: ${response.statusText}`);
96
+ }
97
+ let sync_push_cloud_response = await results.json();
98
+
99
+ // Try to parse as JSON
100
+ try {
101
+ if (!sync_push_cloud_response.state) throw new Error(`syncPushCloud returned error: ${sync_push_cloud_response.message}`);else console.log('syncPushCloud upload response:', sync_push_cloud_response.message);
102
+ return true; // Return true on successful upload
103
+ } catch (parseError) {
104
+ console.error('syncPushCloud : JSON parse error:', parseError);
105
+ throw new Error(`syncPushCloud raised error: ${parseError}`);
106
+ }
107
+ } catch (error) {
108
+ if (true) {
109
+ console.error('syncPushCloud upload error details:', error);
110
+ }
111
+ throw error;
112
+ }
113
+ };
114
+ setPicture = data => {
115
+ console.log("setPicture => Fake procedure canbe deleted !");
116
+ };
117
+
118
+ //-----------------------------------------
119
+ convert_blob_picture_into_cloud_file = async pictureBlob => {
120
+ try {
121
+ console.log("Received pictureBlob in uploadPicture:cloud_url_prefix -> ", pictureBlob.cloud_url_prefix);
122
+ if (!pictureBlob || !pictureBlob.data) {
123
+ //Reset picture
124
+ this.setPicture("");
125
+ return;
126
+ }
127
+ if (pictureBlob.isBlobUrl && pictureBlob.data.startsWith('blob:') && pictureBlob.cloud_url_prefix) {
128
+ let updloadSucces = await this.uploadToDatasyncCloud(pictureBlob); // Upload the image to custom Datasync cloud
129
+ if (updloadSucces) {
130
+ //Clear the data URL to free memory since the image is now uploaded and accessible via cloud URL
131
+ if (pictureBlob.data && pictureBlob.data.startsWith('blob:')) {
132
+ URL.revokeObjectURL(pictureBlob.data);
133
+ }
134
+ this.setPicture(pictureBlob.cloud_url_prefix); //Display the image using the cloud URL only if upload succeeded
135
+ _reactToastify.toast.success("Image uploadée");
136
+ console.log("pictureBlob->", pictureBlob);
137
+
138
+ //inform parent component of the new cloud URL for the uploaded image
139
+ this.props.uploadPicture({
140
+ data: pictureBlob.cloud_url_prefix
141
+ });
142
+ } else {
143
+ console.error("Upload to Datasync cloud failed - no success response received");
144
+ throw new Error("Upload to Datasync cloud failed - no success response received");
145
+ }
146
+ }
147
+ } catch (error) {
148
+ _reactToastify.toast.error("Erreur lors du téléchargement de l'image");
149
+ console.error("Upload error:", error);
150
+ }
151
+ };
152
+
23
153
  //-----------------------------------------------------------------------------------------------------------------------------------------
24
154
  reduceBase64Image = e => {
25
155
  let imageSource = e.path && e.path[0] || e.srcElement; //Safari compliancy
26
156
 
27
- alert("reduceBase64Image !");
28
157
  if (this.debugging) console.log("imageSource = ", imageSource);
29
158
  var canvas = document.createElement('canvas'),
30
159
  context,
@@ -100,7 +229,6 @@ class DsBlob extends _react.Component {
100
229
  reduceBinaryImage = e => {
101
230
  let imageSource = e.path && e.path[0] || e.srcElement; //Safari compliancy
102
231
 
103
- alert("reduceBinaryImage !");
104
232
  if (this.debugging) console.log("imageSource = ", imageSource);
105
233
  var canvas = document.createElement('canvas'),
106
234
  context,
@@ -172,6 +300,17 @@ class DsBlob extends _react.Component {
172
300
  // Store both display URL and binary data
173
301
  this.setData(blobUrl, binaryData);
174
302
  this.props.uploadPicture({
303
+ data: this.props.cloud_url_prefix,
304
+ // Pass the cloud URL for display
305
+ binaryData: null,
306
+ // Clear binary data since we now have a cloud URL
307
+ cloud_url_prefix: this.props.cloud_url_prefix,
308
+ // Pass cloud URL prefix if needed for parent component
309
+ isBlobUrl: false // The final URL is not a blob URL, it's a cloud URL
310
+ });
311
+
312
+ //Call the upload callback with both blob URL for display and binary data for upload
313
+ this.convert_blob_picture_into_cloud_file({
175
314
  data: blobUrl,
176
315
  // For display in img tag
177
316
  binaryData: binaryData,
@@ -193,7 +332,6 @@ class DsBlob extends _react.Component {
193
332
  var image = document.createElement('img');
194
333
  image.onload = this.reduceBase64Image;
195
334
  console.log("storeBase64ImageToImg:e.currentTarget.result = ", e.currentTarget.result);
196
- alert("storeBase64ImageToImg !");
197
335
  image.src = e.currentTarget.result;
198
336
  };
199
337
 
@@ -202,7 +340,6 @@ class DsBlob extends _react.Component {
202
340
  var image = document.createElement('img');
203
341
  //2Do DEBUG image.onload = this.reduceImage;
204
342
  console.log("storeBinaryImageToImg:e.currentTarget.result = ", e.currentTarget.result);
205
- alert("storeBinaryImageToImg !");
206
343
  // Convert ArrayBuffer to Blob URL since image.src cannot accept ArrayBuffer directly
207
344
  // Use the detected image type from the original file
208
345
  const imageType = this.currentImageType || 'image/jpeg'; // fallback to jpeg
@@ -225,7 +362,6 @@ class DsBlob extends _react.Component {
225
362
  readImageAsBase64 = async aPictureFile => {
226
363
  let _reader = new FileReader();
227
364
  console.log("readImageAsBase64:aPictureFile = ", aPictureFile);
228
- alert("readImageAsBase64 !");
229
365
  _reader.onload = this.storeBase64ImageToImg;
230
366
  _reader.readAsDataURL(aPictureFile); //The readAsDataURL() method of the FileReader interface is used to read the contents of the specified file's data as a base64 encoded string.
231
367
  };
@@ -234,7 +370,6 @@ class DsBlob extends _react.Component {
234
370
  readImageAsBinary = async aPictureFile => {
235
371
  let _reader = new FileReader();
236
372
  console.log("readImageAsBinary:aPictureFile = ", aPictureFile);
237
- alert("readImageAsBinary !");
238
373
 
239
374
  // Store the image type for use in storeBinaryImageToImg
240
375
  this.currentImageType = aPictureFile.type;
@@ -260,7 +395,7 @@ class DsBlob extends _react.Component {
260
395
  cleanupBlobUrl = () => {
261
396
  // Only show alert if not in test environment
262
397
  if (typeof jest === 'undefined') {
263
- alert("cleanupBlobUrl !");
398
+ console.log("cleanupBlobUrl !");
264
399
  }
265
400
  // Revoke blob URL if it exists to prevent memory leaks
266
401
  if (this.state.data && this.state.data.startsWith('blob:')) {
@@ -356,7 +491,6 @@ class DsBlob extends _react.Component {
356
491
  return this.state.binaryData || this.props.binaryData || null;
357
492
  };
358
493
 
359
- //-----------------------------------------------------------------------------------------------------------------------------------------
360
494
  //-----------------------------------------------------------------------------------------------------------------------------------------
361
495
  // Data getter and setter methods for read-write access
362
496
  getData = () => {
@@ -446,7 +580,17 @@ class DsBlob extends _react.Component {
446
580
  type: "button",
447
581
  value: "Effacer",
448
582
  onClick: this.resetUpload
449
- })));
583
+ })), /*#__PURE__*/_react.default.createElement(_reactToastify.ToastContainer, {
584
+ position: "top-right",
585
+ autoClose: 3000,
586
+ hideProgressBar: false,
587
+ newestOnTop: false,
588
+ closeOnClick: true,
589
+ rtl: false,
590
+ pauseOnFocusLoss: true,
591
+ draggable: true,
592
+ pauseOnHover: true
593
+ }));
450
594
  }
451
595
  }
452
596
  exports.DsBlob = DsBlob;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "datasync-blob",
3
- "version": "1.1.24",
3
+ "version": "1.1.25",
4
4
  "description": "Datasync Blob component",
5
5
  "main": "./dist/components/DsBlob.js",
6
6
  "files": [
@@ -42,5 +42,8 @@
42
42
  },
43
43
  "keywords": [],
44
44
  "author": "",
45
- "license": "ISC"
45
+ "license": "ISC",
46
+ "dependencies": {
47
+ "react-toastify": "^11.1.0"
48
+ }
46
49
  }