I am tring to upload an image to storage (appwrite). As you can see below is that I have the file from client-side but I don't get it to the server-side. I've read the documentation from Appwrite and the file-data needed to upload is available at client-side but to upload it to storage I need that file-data server-side, I get an empty object. Can you help me with a solution for this problem?
Many thanks in advance!
AuthForm.tsx component:
const handleFileChange = async (e: any) => {
if(e.target.files) {
await createFileId(parseStringify(e.target.files[0]))
//It's here
console.log(e.target.files[0])
}
}
user.actions.tsx:
export const createFileId = async (img: any) => {
const {storage} = await createAdminClient();
//Not here
console.log(img)
const promise = storage.createFile(
BUCKET_ID!,
ID.unique(),
img
);
promise.then(function (response) {
console.log(response); // Success
}, function (error) {
console.log(error); // Failure
});
}
When uploading files in a browser environment, you need to wrap the file in FormData. This ensures that the file is properly sent as part of the request to the server.
AuthForm.tsx
const handleFileChange = async (e: any) => {
if (e.target.files) {
const file = e.target.files[0];
// Prepare FormData to upload the file
const formData = new FormData();
formData.append("file", file);
await createFileId(formData);
// The file is here
console.log(file);
}
}
user.actions.tsx
export const createFileId = async (formData: FormData) => {
const { storage } = await createAdminClient();
// Ensure the file data is available in formData
console.log(formData.get("file"));
const promise = storage.createFile(
BUCKET_ID!,
ID.unique(),
formData.get("file") as File
);
promise.then(function (response) {
console.log(response); // Success
}, function (error) {
console.log(error); // Failure
});
}