When building modern web applications, there are scenarios where you need to allow users to download files generated or processed on the server. In this post, I will walk you through the steps to create a downloadable link using a CodeIgniter backend and a TypeScript frontend.
Table of Contents
2. Setting Up the CodeIgniter Backend
3. Setting Up the TypeScript Frontend
1. Overview
In this tutorial, we will create a system where a user can trigger a file download from the frontend. The frontend will be built using TypeScript, and the backend will be managed by CodeIgniter 4. The process involves sending a request from the frontend to the backend, which in turn responds with the file data. The frontend then processes this data and triggers a download in the browser.
2. Setting Up the CodeIgniter Backend
Create the Controller Method
First, let’s set up the CodeIgniter backend. Our controller needs a method to handle the file download.
<?php
namespace App\Controllers;
use CodeIgniter\HTTP\ResponseInterface;
class FileController extends BaseController
{
public function downloadLog()
{
// Retrieve input data
$input = $this->request->getJSON(true);
$filePath = $input['logFilePath'] ?? null;
$logFileName = $input['logFileName'] ?? null;
if (!$filePath || !$logFileName) {
return $this->response->setStatusCode(400, 'Invalid input');
}
if (file_exists($filePath)) {
// Return the file as a response
return $this->response->download($filePath, null);
} else {
return $this->response->setStatusCode(404, 'File not found');
}
}
}
This method handles the file download by checking if the requested file exists and then serving it as a download response. Appropriate error messages are returned if the file is not found or the input is invalid.
3. Setting Up the TypeScript Frontend
Next, we set up the frontend to handle the file download.
Creating the Download Link
We create a download link that users can click to initiate the file download.
// Create a download link that triggers the form submission
const downloadLink = document.createElement('a');
downloadLink.href = '#';
downloadLink.textContent = 'Download Error Log';
downloadLink.onclick = (event) => {
event.preventDefault();
// Trigger the download when the link is clicked
downloadErrorLog();
};
document.body.appendChild(downloadLink);
This creates an anchor tag dynamically, which the user can click to download the error log.
Handling the File Download in the Frontend
The following TypeScript function handles the download process by making a POST request to the backend and processing the response:
function downloadErrorLog() {
// Assuming logFilePath and logFileName are obtained elsewhere
const logFilePath = '/path/to/log/file.log';
const logFileName = 'error_log.log';
// Make the POST request to the backend
this._core.apiPost<Blob>(
'/cw/ppl/contacts/downloadLog',
{
logFilePath,
logFileName
},
(response) => {
// The response is of type Blob
const blob = new Blob([response], { type: 'application/octet-stream' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = logFileName;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url); // Clean up the URL object
document.body.removeChild(a); // Clean up the DOM
},
);
}
4. Putting It All Together
Here’s how the entire system works:
- User Interaction: The user clicks the “Download Error Log” link on the frontend.
- Frontend Request: The frontend sends a POST request to the backend with the file path and name.
- Backend Response: The backend validates the request, locates the file, and returns it as a downloadable response.
- Frontend Processing: The frontend receives the file as a
Blob, creates a URL, and triggers the download in the user’s browser.
5. Conclusion
In this tutorial, we’ve created a system that allows users to download files using a TypeScript frontend and a CodeIgniter 4 backend. The core concepts covered include handling file downloads, using Blob objects in TypeScript, and structuring backend endpoints in CodeIgniter to serve file responses. This approach can be extended to handle different types of files and more complex logic as needed.
By following this guide, you should now be able to implement a similar file download feature in your own web applications.
Feel free to ask any questions or provide feedback in the comments below!
Learn more Creating a Downloadable Link with a CodeIgniter Backend and TypeScript Frontend
