Implementing File Downloads with Custom Filenames in Frontend Applications
Frontend file downloads often require displaying custom filenames, which differs from standard file uploads or Excel operations. This guide covers two practical approaches using JavaScript and Vue.js.
Custom Filename Downloasd To download files with specific names, use the Blob API and temporary links. This method ensures the browser displays the intended filename during download.
Steps:
- Retrieve file content via the fetch API.
- Convert the content into a Blob object.
- Generate a temporary URL for the Blob.
- Trigger the download with the custom filename.
Example implementation in Vue:
<template>
<div>
<button @click="initiateDownload(fileData)">Download File</button>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const fileData = ref({
sourceUrl: 'https://example.com/document.pdf',
displayName: 'custom_filename.pdf'
});
const initiateDownload = async (file) => {
try {
const response = await fetch(file.sourceUrl);
const blobData = await response.blob();
const tempUrl = window.URL.createObjectURL(blobData);
const linkElement = document.createElement('a');
linkElement.href = tempUrl;
linkElement.download = file.displayName;
document.body.appendChild(linkElement);
linkElement.click();
window.URL.revokeObjectURL(tempUrl);
document.body.removeChild(linkElement);
} catch (error) {
console.error('Download failed:', error);
}
};
return { fileData, initiateDownload };
}
};
</script>
Direct Link Downloads For scenarios where custom filenames are unnecessary, use HTML anchor attributes. This metthod is simpler but relies on the server providing the filename.
Example using Elemant UI in Vue:
<el-table-column label="File Content" align="center" prop="url">
<template #default="{ row }">
<el-image
v-if="row.fileType.includes('image')"
class="image-preview"
lazy
:src="row.url"
:preview-src-list="[row.url]"
fit="cover"
/>
<el-link
v-else-if="row.fileType.includes('pdf')"
type="primary"
:href="row.url"
:underline="false"
target="_blank"
>
View PDF
</el-link>
<el-link
v-else
type="primary"
:href="row.url"
:download="row.fileName"
:underline="false"
target="_blank"
>
Download File
</el-link>
</template>
</el-table-column>
The key element is the <el-link> with the download attribute, which specifies the filename for the download.