From 86ceaa588118ecf224eab06820016a0d052a931c Mon Sep 17 00:00:00 2001 From: "Navy.gif" Date: Tue, 29 Nov 2022 12:21:36 +0200 Subject: [PATCH] uploading avatars functionality --- src/pages/Home.js | 40 +++++++++++++++++++++++++++++++++++++--- src/util/Util.js | 23 ++++++++++++++++------- 2 files changed, 53 insertions(+), 10 deletions(-) diff --git a/src/pages/Home.js b/src/pages/Home.js index 38fca3a..7697910 100644 --- a/src/pages/Home.js +++ b/src/pages/Home.js @@ -84,6 +84,39 @@ const ThirdPartyConnections = ({user}) => { const Profile = () => { const [user] = useLoginContext(); + const [file, setFile] = useState(null); + const fileSelector = useRef(); + const [error, setError] = useState(null); + + // For some reason this has to be done for onDrop to work + const onDragOver = (event) => { + event.stopPropagation(); + event.preventDefault(); + }; + + const onDrop = (event) => { + event.preventDefault(); + const { dataTransfer } = event; + if (!dataTransfer.files.length) return; + + const [file] = dataTransfer.files; + fileSelector.value = file.name; + setFile(file); + }; + + const submit = async ({target: button}) => { + button.disabled = true; + if (!file) return; + + const body = new FormData(); + body.set('file', file, file.name); + // body.set('name', file.name); + + const response = await post('/api/user/avatar', body, { headers: null }); + if (!response.success) setError(response.message); + else fileSelector.current.value = null; + button.disabled = false; + }; return
@@ -97,12 +130,13 @@ const Profile = () => {

Change Profile Picture

-
diff --git a/src/util/Util.js b/src/util/Util.js index 5f86e16..8c45c5f 100644 --- a/src/util/Util.js +++ b/src/util/Util.js @@ -55,14 +55,23 @@ const parseResponse = async (response) => { return { ...base, message: await response.text() }; }; -export const post = async (url, body) => { - const response = await fetch(url, { +export const post = async (url, body, opts = {}) => { + + const options = { method: 'post', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify(body) - }); + body + }; + + if (opts.headers !== null) { + options.headers = { + 'Content-Type': 'application/json', + ...opts.headers || {} + }; + } + + if (options.headers && options.headers['Content-Type'] === 'application/json' && body) options.body = JSON.stringify(body); + + const response = await fetch(url, options); return parseResponse(response); };