Page 1 of 1

Custom File Ajax file upload

Posted: Sat Mar 09, 2024 11:54 pm
by andyrav

Hi
When within a custom file with include common ticked the function uploadFiles returning:

Status
401
Unauthorized
VersionHTTP/1.1
Transferred131.63 kB (0 B size)
Referrer Policystrict-origin-when-cross-origin
DNS ResolutionSystem

i have tried adding

<input type="hidden" name="'.$TokenNameKey.'" value="'.$TokenName.'">
<input type="hidden" name="'.$TokenValueKey.'" value="'.$TokenValue.'">

any ideas why. File upload works find within a normal table.

My code

<input class="form-control w-50 p-3 " type="file" id="id" name="name" accept=".wav"  onchange="uploadFiles(this);">

function uploadFiles(el) {
	let files = el.files, // Get FileList object
		name = el.name,
		url = "/api/upload",
		xhr = new XMLHttpRequest(),
		fd = new FormData();
	xhr.responseType = "json";
	xhr.open("POST", url, true);
	// xhr.setRequestHeader("X-Authorization", "Bearer " + store.JWT); // Set JWT header, if necessary
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4 && xhr.status == 200 && xhr.response) { // Files uploaded
			if (xhr.response.filetoken) // Check file token
				var respons = JSON.parse(JSON.stringify(xhr.response));
				console.log(xhr.response.filetoken);
				filename = respons.files.name.name;
				folderid = xhr.response.filetoken;
		}
	};
	Array.from(files).forEach(file => fd.append(name, file)); // Append File object to form data
	xhr.send(fd);
}

Re: Custom File Ajax file upload

Posted: Sun Mar 10, 2024 10:10 am
by arbei

You need to login first, get the JWT, store it, and send it with all subsequent requests (i.e. the store.JWT) in the header, see Authenticate User with JWT (JSON Web Token). (You don't need $TokenName and $TokenKey.)


Re: Custom File Ajax file upload

Posted: Sun Mar 10, 2024 7:36 pm
by andyrav

So i see there is a function GetJwtToken()
Setting
xhr.setRequestHeader("X-Authorization", "Bearer " + '<?php echo GetJwtToken() ?>'); // Set JWT header, if necessary
Worked

Many thanks for pointing me in the right direction