Hi I am trying to create an image to the server, but I am always getting an error. Here is the sample code:
let response = await fetch(path);
var blob = await response.blob();
var file = new File([blob], "image.jpg", {
type: "image/jpeg",
});
const data = new FormData();
data.append("files", file);
const { data: files } = await FileRepository.createImage(data);
Failed with Error: {“code”:500000,“level”:“error”,“type”:“ASC”,“timestamp”:1741669277354}
Hello @EmmanKusumi , Thank you for reaching out. Based on our team’s recommendations, we suggest following the official documentation for uploading images:
Image Upload Documentation
Below is an example implementation that aligns with the recommended approach:
import React from 'react';
import { FileRepository } from '@amityco/ts-sdk';
const ImageUpload = () => {
const changeHandler = async (event: React.ChangeEvent<HTMLInputElement>) => {
if (!event.target.files) {
return;
}
const data = new FormData();
data.append('files', event.target.files[0]);
const { data: image } = await FileRepository.uploadImage(data);
return image;
};
return <input type="file" name="file" onChange={changeHandler} />;
};
We recommend implementing this and testing the upload functionality. Please let us know if you encounter any issues or need further assistance.
I am using expo image picker, so I can’t use “React.ChangeEvent”.
I also tried to follow the other sample app that you have, but I am having an issue creating the formData.
formData.append(‘files’, {
name: fileName,
type: fileType,
uri: uri,
});
Error: No overload matches this call.
1 Like
Hello @EmmanKusumi,
Our team suggests trying the following code for image upload:
export async function uploadImageFile(
filePath: string,
perCentCallback?: (percent: number) => void
): Promise<Amity.File<any>[]> {
return await new Promise(async (resolve, reject) => {
const formData = new FormData();
const parts = filePath.split('/');
const fileName = parts[parts.length - 1];
const fileType = Platform.OS === 'ios' ? 'image/jpeg' : 'image/jpg';
const uri =
Platform.OS === 'android' ? filePath : filePath.replace('file://', '');
formData.append('files', {
name: fileName,
type: fileType,
uri: uri,
});
const { data: file } = await FileRepository.uploadImage(
formData,
(percent) => {
perCentCallback && perCentCallback(percent);
}
);
if (file) {
resolve(file);
} else {
reject('Upload error');
}
});
}
Please test this implementation and let us know if the issue persists or if you need further assistance.