Skip to content

Commit

Permalink
test: simplify upload test (#1325)
Browse files Browse the repository at this point in the history
  • Loading branch information
mcollovati authored Feb 21, 2025
1 parent 659d6d5 commit 2d3c18b
Showing 1 changed file with 9 additions and 45 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {useState} from 'react';

import {ViewConfig} from "@vaadin/hilla-file-router/types.js";
//import {UploadEndpoint} from "Frontend/generated/endpoints";
import {UploadEndpoint} from "Frontend/generated/endpoints";

export const config: ViewConfig = {
title: "Upload",
Expand All @@ -22,51 +22,15 @@ export default function UploadView() {
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault(); // Prevent the default form submission behavior
if (file) {
uploadFile(file);
}
};
const uploadFile = (file: File) => {

// const file = new FormData(event.target as HTMLFormElement).get("file");
// const savedFile = await UploadEndpoint.upload("my-test", file);

// Temporary upload logic until Hilla completes multipart form
// support on the client side services
const formData = new FormData();
formData.append("/file", file);
formData.append("hilla_body_part", `{ "name": "my-test" }`);

const csrfCookie = "csrfToken";
const crsfToken = document.cookie.split(";")
.map((c) => c.trim())
.filter(c => c.startsWith(csrfCookie + "="))
.map(c => c.substring(csrfCookie.length +1))[0];
const xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('POST', '/connect/UploadEndpoint/upload', true);
xhr.setRequestHeader("X-CSRF-Token", crsfToken);
// Set up event listeners for progress, completion, etc.
xhr.upload.onprogress = (event) => {
if (event.lengthComputable) {
const percentComplete = (event.loaded / event.total) * 100;
console.log(`Upload progress: ${percentComplete}%`);
}
};
xhr.onload = () => {
if (xhr.status === 200) {
console.log('File uploaded successfully!');
console.log('Response:', xhr.responseText);
setUploadState("File saved to " + xhr.responseText);
} else {
console.error('File upload failed.');
}
};
xhr.onerror = () => {
console.error('Error during file upload.');
};
// Send the request
xhr.send(formData);
UploadEndpoint.upload("my-test", file).then(
savedFile => {
setUploadState(`File saved to "${savedFile}"`);
setFile(null);
},
err => console.log(err)
);

}
};

return (<form id="upload" onSubmit={handleSubmit}>
Expand Down

0 comments on commit 2d3c18b

Please sign in to comment.