Hey there! In this guide, I'll show you how to create a download or "get resource" button in Xano that allows users to access and download images directly from your API endpoints. Just like you can generate a CSV through the API, you can also enable direct access to image resources.
First, you'll need to create an API endpoint that retrieves your images. Here's an example endpoint that fetches an image record based on its ID:
javascript
// Fetch image record by ID
export default async (req, res) => {
const { id } = req.params;
const model = await env.Images.findOne({ where: { id } });
// Return the image record
return res.json(model);
}
When you run this endpoint and pass an image ID, you'll get the entire image record object, including the image URL in the `images` field.
To enable direct access to the image URL, you'll need to add a custom HTTP header that redirects the user to the image URL. Xano provides a handy `HTTP_Headers` utility function for this purpose.
In your function stack, navigate to the `utility functions` section and find the `HTTP_Headers` function. Then, add the following code to define a `Location` header:
javascript
export default (model) => ({
'Location': `%s${sprintf('%s', model.images.url)}`,
});
Here's what's happening:
Now, go back to your API endpoint and update it to use the `HTTP_Headers` function you just created:
javascript
import HTTP_Headers from 'utilities/HTTP_Headers?res=base64';
export default async (req, res) => {
const { id } = req.params;
const model = await env.Images.findOne({ where: { id } });
// Set the Location header for redirection
res.setHeaders(HTTP_Headers(model));
// No need to return a response
return res.status(302).send();
}
Here's what's happening:
Now, when you run your API endpoint with a valid image ID, you should be redirected directly to the image URL. You can test this in a few ways:
That's it! You've now learned how to create a "get resource" button in Xano that allows users to download or access images directly from your API endpoints. This technique can be useful for building image galleries, file hosting services, or any application that requires direct access to image resources.
This transcript was AI generated to allow users to quickly answer technical questions about Xano.
I found it helpful
I need more support