-
Notifications
You must be signed in to change notification settings - Fork 47
/
account.html
102 lines (85 loc) · 2.78 KB
/
account.html
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
<html>
<body>
<h1>Edit your account</h1>
<hr>
<h2>Your avatar</h2>
<input type="file" id="file-input">
<p id="status">Please select a file</p>
<img style="border:1px solid gray;width:300px;" id="preview" src="/static/media/default.png">
<h2>Your information</h2>
<form method="POST" action="/submit-form/">
<input type="hidden" id="avatar-url" name="avatar-url" value="/static/media/default.png">
<input type="text" name="username" placeholder="Username"><br>
<input type="text" name="full-name" placeholder="Full name"><br><br>
<hr>
<h2>Save changes</h2>
<input type="submit" value="Update profile">
</form>
<script type="text/javascript">
/*
Function to carry out the actual POST request to S3 using the signed request from the Python app.
*/
function uploadFile(file, s3Data, url){
const xhr = new XMLHttpRequest();
xhr.open('POST', s3Data.url);
xhr.setRequestHeader('x-amz-acl', 'public-read');
const postData = new FormData();
for(key in s3Data.fields){
postData.append(key, s3Data.fields[key]);
}
postData.append('file', file);
xhr.onreadystatechange = () => {
if(xhr.readyState === 4){
if(xhr.status === 200 || xhr.status === 204){
document.getElementById('preview').src = url;
document.getElementById('avatar-url').value = url;
}
else{
alert('Could not upload file.');
}
}
};
xhr.send(postData);
}
/*
Function to get the temporary signed request from the Python app.
If request successful, continue to upload the file using this signed
request.
*/
function getSignedRequest(file){
const xhr = new XMLHttpRequest();
xhr.open('GET', `/sign-s3?file-name=${file.name}&file-type=${file.type}`);
xhr.onreadystatechange = () => {
if(xhr.readyState === 4){
if(xhr.status === 200){
const response = JSON.parse(xhr.responseText);
uploadFile(file, response.data, response.url);
}
else{
alert('Could not get signed URL.');
}
}
};
xhr.send();
}
/*
Function called when file input updated. If there is a file selected, then
start upload procedure by asking for a signed request from the app.
*/
function initUpload(){
const files = document.getElementById('file-input').files;
const file = files[0];
if(!file){
return alert('No file selected.');
}
getSignedRequest(file);
}
/*
Bind listeners when the page loads.
*/
(() => {
document.getElementById('file-input').onchange = initUpload;
})();
</script>
</body>
</html>