I'm trying to upload file with Gitlab API and everything is working correctly. I'm using the curl command with the terminal like:
curl --header "PRIVATE-TOKEN: my-private-token" \
--upload-file "path to"/file \
"https://my-gitlab-url.it/api/v4/projects/<projectID>/packages/generic/<name_packaged>/<version>/<file>"
Now, because the curl via command line is a bit sketchy for "normal user", I'm developing a GUI to upload the file.
I have created a File Input Form with Boostrap with the code
<div class="mb-3">
<label for="formFile" class="form-label">Chose the file</label>
<input class="form-control" type="file" id="formFile" />
</div>
And the javascript that read the data
var select_file = document.getElementById("formFile");
function onChangeSelectFile() {
var value = select_file.files;
var text = select_file.files[0].name;
console.log(value, text);
}
select_file.onchange = onChangeSelectFile;
Now, I would like to use fetch
with
fetch("https://my-gitlab-url.it/api/v4/projects/<projectID>/packages/generic/<name_packaged>/<version>/<file>", {
headers: {
"PRIVATE-TOKEN": "my-private-token",
},
})
Clearly I miss the part where I send the actual file and I can't find a way to do it.
According to the documentation is a PUT
request
So it really was a PUT
request:
fetch(file_string, {
method: "PUT",
headers: {
"PRIVATE-TOKEN": "my-private-token",
},
body: formData,
})
.then((response) => response.json())
.then((data) => {
console.log("File uploaded successfully:", data);
})
.catch((error) => {
console.error("Error uploading file:", error);
});
}
where
var select_file = document.getElementById("formFile").files[0];
formData.append("file", select_file);