how to upload a file to backend in typescript

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.ts
import axios from 'axios';

const formData = new FormData();
formData.append('file', file); // `file` is the file object obtained from a file input element

axios.post('/api/upload', formData, {
  headers: {
    'Content-Type': 'multipart/form-data'
  }
})
.then(response => {
  console.log(response.data);
})
.catch(error => {
  console.log(error);
});
354 chars
17 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