4

I am trying to set the types for a file upload, but I can not believe I have to define every single property on the file object

export type FileProps = {
  path: string 
  lastModified: number
  slice: () => void
  stream: () => void
  text: () => void
  arrayBuffer: ArrayBuffer
  name: string
  size: number
  type: string
}

const [files, setFiles] = useState<FileProps[]>([])

I upload a few files and store them on the state, but then when I try to add to the form

const formData = new FormData()

for (const file of files) {
  formData.append('files', file)
}

I get an error on file

enter image description here

2
  • I think you want to use file.text if that is a string representation of the text of the file. You could also convert the ArrayBuffer to Blob or use the stream to create the blob. Commented Jul 1, 2021 at 17:23
  • I need to get the whole file with with name, size etc. as I am passing the file to the back end, it works if I turn every type to any but I get the yellow warning, there must be a better way Commented Jul 1, 2021 at 17:26

2 Answers 2

10

If you just use File, then you get exactly what you want:

const [files, setFiles] = useState<File[]>([])

const formData = new FormData()

for (const file of files) {
  formData.append('files', file)
}

That should get you all the fields documented here: https://developer.mozilla.org/en-US/docs/Web/API/File

See playground

Sign up to request clarification or add additional context in comments.

Comments

0

The second argument of the FormData.append method is Blob or USVString.

You had mentioned in a comment that the entire structure needs to be sent to the backend. So, you need to convert the FormData instance to a blob.

for (const file of files) {
  formData.append('files', new Blob([JSON.stringify(file)], {type : 'text/html'});)
}

2 Comments

I get Argument of type 'string' is not assignable to parameter of type 'BlobPart[] | undefined'.
Answer edited. The blob constructor needs a type of an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.