We are trying to build a zip download feature for documents. The zip can contain files stored in ContentVersions and external files.
It works fine for external files.
But due to CORS, we cannot access the normal download servlet /sfc/servlet.shepherd/version/download/ from lightning JS since that redirects to files.force.com and the CORS restrictions don't allow accessing the data from there. I added file.force.com to trusted URLs to fix the CSP error, but the CORS error remains.
So I built a small Apex function that should return the file content:
public static Blob getFileContents(String docId) { try { ContentVersion conVer = [ SELECT Id, VersionData FROM ContentVersion WHERE (Id = :docId OR ContentDocumentId = :docId) AND isLatest = TRUE WITH USER_MODE ]; return conVer.VersionData; } catch (Exception e) { throw new AuraHandledException(e.getMessage()); } }but when I call that from lightning js, I get a 500 response and no log. The 500 also happens when called from debug console.
Salesforce support says finding the source of the 500 would need developer support and thats not covered by the standard support plan.
So is there any other on-platform way to get the file contents of a contentDocument by lightning code?
I am aware that If I were using FilesConnect I could use the shepherd servlet for zip download but that is not feasible for other reasons.
Please try below pointers and try them with your solutions
- Base64 Encoding: Retrieve file contents as Base64 encoded strings from Apex and handle file creation in JavaScript.
- Visualforce Page: Create a Visualforce page acting as a proxy to download files, bypassing CORS restrictions.
- Apex REST Service: Develop a RESTful web service in Apex to serve file contents, accessible from Lightning components.
- Debugging and Error Handling: Enhance error handling in the Apex method and attempt to debug the cause of the 500 error using debug statements or system debug logs.
- Governor Limits and Permissions: Ensure the Apex method complies with governor limits and users have necessary permissions to access ContentVersion records.
- Reevaluate Architecture: Consider alternative storage solutions or architectures that circumvent CORS restrictions and better suit your requirements.
By implementing one or more of these approaches and ensuring proper error handling and debugging, you can potentially resolve the issue of accessing file contents from ContentVersions in Lightning components despite CORS restrictions.