To upload a file from the front-end to the back-end in TypeScript, you can use the FormData
class to construct a form containing the file, and then send the form to the backend using an HTTP client such as axios
.
Here is an example of how to do this using axios
:
index.ts354 chars17 lines
In this code, we first create a new instance of FormData
and append the file to it using the append()
method. Then, we use axios.post()
to send the form data to the desired API endpoint (in this example, /api/upload
). We also set the Content-Type
header to multipart/form-data
, which is necessary for file uploads.
When the request is successful, the response will be logged to the console. If there is an error, the error will be logged instead. Note that you'll need to handle the response appropriately on the backend as well.
gistlibby LogSnag