Custom File Ajax file upload

This public forum is for user-to-user discussions of PHPMaker. Note that this is not support forum.
Post Reply
andyrav
User
Posts: 641

Custom File Ajax file upload

Post 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);
}

arbei
User
Posts: 9384

Post 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.)


andyrav
User
Posts: 641

Post 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


Post Reply