Here’s what I came up with to solve that issue. Originally I had it set so that everything had a download link but that got a little cluttered on my view. So I modified it so that it kept the download link for anything other than the native viewer files.
I have this in a Grid view for documents associated with a record. I have inline editing enabled for the grid but I used the KTL to disable inline for the ‘File’ column. I had to do that because if I clicked on the download link, knack would just spin about while popping up the edit bubble to add a file. Once I disabled inline editing for that column it would download like expected.
$(document).on('knack-view-render.any', function (event, view, data) {
setFileViewer();
});
function setFileViewer() {
$('.kn-view-asset').each(function() {
let arr = $(this).text().split('.');
let extension = arr[arr.length - 1].toLowerCase();
let fileName = $(this).attr('data-file-name'); // Get filename
let fileId = $(this).attr('data-asset-id'); // Get file ID
let fileUrl = 'https://api.knack.com/v1/applications/' + Knack.app.id + '/download/asset/' + fileId + '/' + fileName;
// Get viewer URL
let viewerUrl = fileViewer(extension, fileUrl);
// Create viewer link
let viewerLink = $('<a>')
.attr('href', viewerUrl)
.attr('target', '_blank')
.text($(this).text());
// Replace current text with viewer link
$(this).replaceWith(viewerLink);
// Append a download link if the file is an Office document or an unsupported file
if (shouldShowDownloadLink(extension) || isOfficeFile(extension)) {
let downloadLink = $('<a>')
.attr('href', fileUrl)
.attr('download', fileName)
.text(' Download')
.css({
'margin-left': '10px',
'color': 'blue',
'text-decoration': 'underline',
'cursor': 'pointer'
});
viewerLink.after(downloadLink);
}
});
}
// Function to determine if a download link should be shown for unsupported files
function shouldShowDownloadLink(extension) {
let supportedExtensions = [
"pdf", "txt", "html", "jpg", "jpeg", "bmp", "png",
"mpg", "mpeg", "wmv", "mp4", "dvr-ms", "avi", "mov", "ogg", "mkv"
];
return !supportedExtensions.includes(extension);
}
// Function to check if a file is an Office file (so we always show a download link)
function isOfficeFile(extension) {
let officeExtensions = [
"docx", "docm", "doc", "dotx", "dotm", "dot",
"xlsx", "xlsm", "xls",
"ppts", "ppt", "pptx"
];
return officeExtensions.includes(extension);
}
// Function to determine viewer URL
function fileViewer(e, url) {
switch (e) {
case "pdf":
case "txt":
case "html":
case "jpg":
case "jpeg":
case "bmp":
case "png":
case "mpg":
case "mpeg":
case "wmv":
case "mp4":
case "dvr-ms":
case "avi":
case "mov":
case "ogg":
case "mkv":
return url;
case "docx":
case "docm":
case "doc":
case "dotx":
case "dotm":
case "dot":
case "xlsx":
case "xlsm":
case "xls":
case "ppts":
case "ppt":
case "pptx":
return 'https://view.officeapps.live.com/op/view.aspx?src=' + url;
default:
return 'https://docs.google.com/gview?url=' + url;
}
}