I'm trying to upload some images to firebase storage but I keep getting the following error in JavaScript.
Error: TypeError: Failed to fetch at HTMLButtonElement.
I tried debugging and it seems to throw this error when I execute
fileList.add(this.convertToFile(multipartFileList.get(multipartFileList.size()-1), fileNameListItem));
in Spring controller.
The strange thing is that the program actually managed to upload all the files in firebase storage, I also tried using postman to test the backend and it works as expected(it returns the download links) but the only things that doesn't seem to work is JavaScript.
This is the code:
HTML:
<input type="file" id="fileUpload" multiple/>
<button id="fileUploadButton" type = "button" > Upload photos</button>
JS:
const fileUploadButton = document.getElementById("fileUploadButton");
document
.querySelector("#fileUpload")
.addEventListener("change", (event) => {
handleImageUpload(event);
});
const handleImageUpload = (event) => {
event.preventDefault();
files = event.target.files;
const formData = new FormData();
for (const file of files) {
formData.append("files", file);
console.log(file)
}
fileUploadButton.addEventListener('click',function(e){
e.preventDefault();
fetch("http://localhost:8080/images/incidents/pics", {
method: "POST",
body: formData,
header: {
"Access-Control-Allow-Origin": "*",
},
}
)
.then((response) => response.json())
.then((data) => console.log(data))
.then((data) => (res = data))
.then(() =>
sessionStorage.setItem("incidents_photo_paths", JSON.stringify(res))
)
.catch((error) => {
console.error("Error:", error);
});e.preventDefault()})
Spring service
private String uploadFile(File file, String fileName) throws IOException {
BlobId blobId = BlobId.of("link-to-my-database", fileName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("media").build();
Credentials credentials = GoogleCredentials.fromStream(new FileInputStream("my-security-key"));
Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();
storage.create(blobInfo, Files.readAllBytes(file.toPath()));
return String.format(DOWNLOAD_URL, URLEncoder.encode(fileName, StandardCharsets.UTF_8));
}
private File convertToFile(MultipartFile multipartFile, String fileName) throws IOException {
File tempFile = new File(fileName);
try (FileOutputStream fos = new FileOutputStream(tempFile)) {
fos.write(multipartFile.getBytes());
fos.close();
}
return tempFile;
}
public ListResponse uploadMultipleFiles(List<MultipartFile> multipartFileList) {
List<String> fileNameList = new ArrayList<>();
List<File> fileList= new ArrayList<>();
List<String> tempUrlList = new ArrayList<>();
try {
for (MultipartFile multipartFile: multipartFileList
) {
fileNameList.add(multipartFile.getOriginalFilename());
}
for (String fileNameListItem: fileNameList
) {
fileNameListItem = UUID.randomUUID().toString().concat(this.getExtension(fileNameListItem));
File file =this.convertToFile(multipartFileList.get(multipartFileList.size()-1), fileNameListItem);
fileList.add(this.convertToFile(multipartFileList.get(multipartFileList.size()-1), fileNameListItem));
tempUrlList.add(this.uploadFile(file, fileNameListItem));
file.delete();
}
return new ListResponse(tempUrlList) ;
} catch (Exception e) {
e.printStackTrace();
return new ListResponse("Error, could not upload!");
}
}