Having trouble with displaying an image
The goal is to display an authenticated user's avatar pic.
back-end and front-end have separate servers and are using restful api and i'm using vanilla js to send a GET request to get the avatar and show it.
this is what i return in laravel controller:
return response()->file(base_path() . '/storage/app/images/avatars/1.jpeg', ['Content-Type' => 'Image/jpeg']);
// also tryed these but no luck
// return response()->download(Storage::disk('local')->get('images/avatars/1.jpeg'), 'name', ['Content-Type' => 'Image/jpeg']);
// return Storage::disk('local')->get('images/avatars/1.jpeg');
// return response()->file(Storage::disk('local')->get('images/avatars/1.jpeg'));
and this is how i set user's avatar:
Storage::putFileAs('images/avatars/', $request->avatar, $request->accountId, 'private');
and in front-end: (i'm new in front-end and with js)
let token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
let myRequest = new Request('avatar');
let myHeaders = new Headers();
myHeaders.append("Accept", "application/json, text-plain, */*");
myHeaders.append("X-Requested-With", "XMLHttpRequest");
myHeaders.append("X-CSRF-TOKEN", token);
myHeaders.append("Content-Type", 'image/jpeg/jpg');
let init = {
method: 'GET',
mode: 'cors',
credentials: 'same-origin',
headers: myHeaders,
};
fetch(myRequest, init).then((response) => {
console.log(response);
return getBody(response);
}).then((data) => {
console.log(data);
createAppendElm('img', {
'src': 'data:image/jpeg;base64,' + btoa(data),
'alt': 'avatar'
}, getElm('box'));
});
function createAppendElm(tagName, attributes, parentElm) {
var elm = document.createElement(tagName);
for (const attribute in attributes) {
if (Object.hasOwnProperty.call(attributes, attribute)) {
const value = attributes[attribute];
elm.setAttribute(attribute, value);
}
}
parentElm.appendChild(elm);
return elm;
}
function getBody(response) {
const contentType = response.headers.get("content-type");
if (contentType && contentType.indexOf("application/json") !== -1) {
return response.json();
} else {
return response.text();
}
}
console.log(data) shows the binary content of the picture.(���� ...)
any suggestions?
How many English words
do you know?
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
how many words do you know
Powered by Examplum