In a React/Typescript app I have a component that accepts a file:
<div>
<input type="file" {...register('avatar')} />
</div>
along with 2 string values. These values are all saved to FormData:
type FormData = {
handle: string;
role: string;
avatar: File;
};
const {
register,
handleSubmit,
formState: { errors },
} = useForm<FormData>();
I would like to access the avatar file name to use later on, as well as send the file to an AWS bucket like this:
const onSubmit = (data: FormData) => {
console.log(data);
console.log(data.avatar.name);
ReactS3Client.uploadFile(data.avatar, data.handle + Date.now())
.then((data) => console.log(data))
.catch((err) => console.error(err));
There are a few problems happening here. First of all, when I console.log avatar.name it is simply blank. In one of my tests the file was Player.jpg, so I expected it to log "Player". Next, when I check my AWS bucket the file was indeed uploaded but when I try to open it I do not see an image and instead see: [object FileList.
Obviously somewhere in the process I am interacting with the uploaded file incorrectly. How can I access the name of the file and correctly upload it to AWS?
EDIT:
If I console.log(data.avatar); it gives me this:
If I console.log(data.avatar.name); which is an autofill option in VS Code then it simply prints undefined.
If I console.log(data.avatar[0].name); I get this error: Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'File'. Property '0' does not exist on type 'File'.ts(7053).
How can I access that name property?
I believe that console.log(data.avatar[0].name); will give you what you need.