🦊 Search and File Uploads 🦊
Posted on Jun 7th, 2022
🗓️ Today’s Topics
- Implementing search in your application 🔍
- Images
- File Uploads: forms and requests
Example Request with Query Params
Remember the iTunes API? To get search results, you needed to include query params that specified the search fields and terms you wanted to use.
Here’s how you might make a request that uses query params using axios:
// This example depends on having a definition for `searchTerm` in your code
// You'll want to get the value from a search input form field
let url = 'https://drf-library-api.herokuapp.com/api/books'
axios.get(url,
{
params: {search: searchTerm},
headers: {Authorization: 'Token e4881816a58901b630e1148c76ff942fab904a6e'}
})
Example Request to Upload a File
This is an update (notice the PUT verb) to an existing record. In this case you are including the file itself as the body of the request (notice it in the second position as an argument to put()
) and setting specific headers required by the server to handle the binary file attachment.
axios.put(url, file, {
headers: {
Authorization: 'Token ' + token,
'Content-Type': file.type,
'Content-Disposition': `attachment; filename=${file.name}`
}
}).then(res => console.log(res.data))
NOTE: If you Google how to include a file attachment in an ajax request, you’ll see a lot of references to using the FormData object. You can do it that way, but you don’t have to; the above method will work just fine as long as you know how to access the file that is being uploaded by the user.
Here’s info about using FormData objects if you want to know more about that.
See the resources below for more information about using a file input element and accessing a selected file. The useRef()
hook will be helpful to get the files from the input element.