Iam trying to upload a file to the Google Cloud via JavaScript.
But but right now i’m failing miserably.
This is my Code so far:
function uploadFile(){
const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();
let blob;
reader.onload = function(e) {
console.log(file)
blob = new Blob([new Uint8Array(e.target.result)], {type: file.type });
fetch('https://storage.googleapis.com/upload/storage/v1/b/"my_bucket_here"/o', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer "Token here"'
},
body: blob,
})
.then(response => console.log('Success'))
.catch(error => console.log(error));
};
reader.readAsArrayBuffer(file);
}
-
At first I try to get the Token from my input tag in my html File
const file = document.querySelector('input[type=file]').files[0];
Html:
<input type="file" id="upload" name="upload" class="box">
- Then I have the reader.onload function where I store the File into a Blob
the logging of the File shows me the selectet File so the Code where i get my File should work….
- After that Iam trying to Post my Blob via fetch Api to my bucket
I think this is the point where the Code fails, because I get an 400 Http Error.
POST https://storage.googleapis.com/upload/storage/v1/b/yaec_example/o 400
reader.onload @ upload.js:11
load (async)
uploadFile @ upload.js:7
onclick @ index.html?_ijt=v0tmlt6ecn7lbgsgmve0d34dra:49
It would be great if someone experienced in Google Cloud Upload could help me…
Thanks!