forked from OVDR-GRP-Team07/OVDR
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUploadImage.js.html
More file actions
252 lines (213 loc) · 8.8 KB
/
UploadImage.js.html
File metadata and controls
252 lines (213 loc) · 8.8 KB
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
250
251
252
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JSDoc: Source: UploadImage.js</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>
<body>
<div id="main">
<h1 class="page-title">Source: UploadImage.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>/**
* UploadImage.js - Upload or capture a full-body image for virtual try-on.
*
* @fileoverview Allows users to preview an image (from camera or file),
* confirm submission, and upload to backend. Delays global state changes
* until the user confirms submission.
*
* @author
* Peini SHE & Zixin DING
*
*/
/* Purpose:
* - Allow users to upload or capture full-body images
* - Preview before upload, avoid immediate state changes
* - Upload image to backend only after confirmation
* - Prevent overwriting previous image if "Exit" is clicked
* - Cache-busting via ?t=timestamp to force image refresh
*
* Modifications by Zixin Ding:
* - Decoupled preview and upload logic
* - Delayed backend upload until Submit
* - Added imageSource to track origin (camera/file)
* - Prevented global state overwrite on cancel
* - Fixed image caching issues using timestamp URL
*/
import { useState, useRef, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import "./UploadImage.css";
import Webcam from "react-webcam";
function UploadImage({ uploadedImage, setUploadedImage, userId}) {
const navigate = useNavigate();
const [imagePreview, setImagePreview] = useState(null);
const previousImageRef = useRef(uploadedImage);
const [cameraOpen, setCameraOpen] = useState(false);
const webcamRef = useRef(null);
// Track where the image came from
const [imageSource, setImageSource] = useState(null); // "camera" | "file"
useEffect(() => {
if (cameraOpen) {
console.log("Camera Open.");
} else {
console.log("Camera Closed.");
}
}, [cameraOpen]);
/**
* Handle file input and preview the image without uploading.
* @param {React.ChangeEvent<HTMLInputElement>} event
*/
const handleImageUpload = async (event) => {
const file = event.target.files[0];
if (file) {
setCameraOpen(false); // Make sure camera closes
setImageSource("file"); // Set source flag
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = async () => {
const base64String = reader.result;
setImagePreview(base64String); // Just preview
};
}
};
/**
* Capture a photo from the webcam and preview it.
*/
const capturePhoto = async () => {
if (webcamRef.current) {
const imageSrc = webcamRef.current.getScreenshot();
setImagePreview(imageSrc);
setImageSource("camera");
setCameraOpen(false);
}
};
/**
* Upload the confirmed image file to the backend server.
* @param {File} file - The image file to be uploaded
* @returns {Promise<string|undefined>} - Uploaded image URL if successful
*/
// UPDATED: This only runs when user clicks "Submit"
const uploadToBackend = async (file) => {
const formData = new FormData();
formData.append("file", file);
formData.append("user_id", userId);
try {
// const response = await fetch("http://localhost:5000/upload_image", {
// method: "POST",
// body: formData,
// });
const response = await fetch("/upload_image", {
method: "POST",
body: formData
});
const data = await response.json();
if (response.ok) {
// NEW: Full image URL with timestamp to prevent caching
const fullImageUrl = `http://localhost:5000/${data.image_path.replace(/\\/g, "/")}?t=${Date.now()}`;
console.log("Uploaded Image URL:", fullImageUrl);
return fullImageUrl;
} else {
console.error("Upload failed:", data.error);
}
} catch (error) {
console.error("Error uploading image:", error);
}
};
/**
* On user confirmation, convert preview to file and send to backend.
*/
// NEW: Only upload and update when user clicks "Submit"
const handleSubmit = async () => {
if (!imagePreview) return;
try {
const blob = await fetch(imagePreview).then(res => res.blob());
const file = new File([blob], "submitted_image.jpg", { type: "image/jpeg" });
const uploadedUrl = await uploadToBackend(file);
if (uploadedUrl) {
setUploadedImage(uploadedUrl); // Set global state with backend image path
navigate("/tryon"); // Navigate only after success
} else {
alert("Image upload failed.");
}
} catch (error) {
console.error("Failed to submit image:", error);
alert("Failed to upload image. Please try again.");
}
};
/**
* Exit preview mode, revert to previous uploaded image.
*/
const handleExit = () => {
setImagePreview(previousImageRef.current);
setUploadedImage(previousImageRef.current);
navigate(-1);
};
return (
<div className="upload-container">
<h1>Upload or Capture a Photo</h1>
{!imagePreview && !cameraOpen && (
<div className="upload-options">
<button className="upload-btn" onClick={() => setCameraOpen(true)}>📷 Use Camera</button>
<label className="upload-btn">
📁 Upload Image
<input type="file" accept="image/*" onChange={handleImageUpload} hidden />
</label>
</div>
)}
{cameraOpen && (
<div className="camera-container" >
<Webcam
audio={false}
ref={webcamRef}
screenshotFormat="image/png"
className="webcam-view"
videoConstraints={{
width: 384,
height: 512,
facingMode: "user", // front-facing camera
}}
/>
<div className="button-row">
<button className="exit-btn" onClick={handleExit}>Exit</button>
<button className="action-btn" onClick={capturePhoto}>Capture</button>
</div>
</div>
)}
{imagePreview && (
<div className="preview-container">
<img src={imagePreview}
alt="Preview"
className="preview-image"
key={imagePreview} />
<div className="button-row">
<button className="exit-btn" onClick={handleExit}>Exit</button>
<button className="action-btn" onClick={handleSubmit}>Submit</button>
</div>
</div>
)}
</div>
);
}
export default UploadImage;
</code></pre>
</article>
</section>
</div>
<nav>
<h2><a href="index.html">Home</a></h2><h3>Global</h3><ul><li><a href="global.html#App">App</a></li><li><a href="global.html#ClothesDetail">ClothesDetail</a></li><li><a href="global.html#FullCloset">FullCloset</a></li><li><a href="global.html#History">History</a></li><li><a href="global.html#Home">Home</a></li><li><a href="global.html#Login">Login</a></li><li><a href="global.html#Register">Register</a></li><li><a href="global.html#SaveImage">SaveImage</a></li><li><a href="global.html#TryOn">TryOn</a></li><li><a href="global.html#fetchImageAsBase64">fetchImageAsBase64</a></li><li><a href="global.html#root">root</a></li></ul>
</nav>
<br class="clear">
<footer>
Documentation generated by <a href="https://github.com/jsdoc/jsdoc">JSDoc 4.0.4</a> on Tue Apr 01 2025 12:14:54 GMT+0800 (中国标准时间)
</footer>
<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>