Question Sakthivel Perumal · Aug 16, 2023

How to download files in server from CSP page using MIME data ?

I have a webpage in CSP in which there is a link to download files (files are located in specific folder). When the user clicks on the link , it has to download the file into their local machine. Attached code for both upload and download the file from server, upload is working and download is printing the file in webpage rather than downloading it. Appreciate your help.

Upload (Working fine): 

set dir="/usr/bin/local/myfiles/
    Set mimeData = %request.GetMimeData("file")
    Set fileType = mimeData.Attributes("ContentType")
    Set docType=$Select(fileType="image/jpeg":"jpg",fileType="application/pdf":"pdf",fileType="text/plain":"txt",1:"pdf")
    Set destination = ##class(%Stream.FileBinary).%New()
    Set destination.Filename = dir_fileName
    do destination.CopyFrom(mimeData)

Download (Not Working) :

set header="attachment;filename="_dir_fileName
    Set%response.ContentType = "application/pdf"Do%response.SetHeader("Content-Disposition",header)
    Set%response.NoCharSetConvert=1Set%response.Headers("Access-Control-Allow-Origin")="*"Set stream=##class(%Stream.FileBinary).%New()
    Set sc=stream.LinkToFile(dir_fileName)
    write stream.OutputToDevice()
Product version: IRIS 2023.1

Comments

Ashok Kumar T · Aug 16, 2023

Hi @Sakthivel Perumal 

Can you try the below sample to download file from the directory

Class Samples.CSPFileDownload Extends%CSP.Page
{
Parameter CONTENTTYPE As STRING = "application/text";ClassMethod OnPage() As%Status
{
    do%stream.OutputToDevice()
    return$$$OK
}
ClassMethod OnPreHTTP() As%Boolean
{
    #; your directory and fileset file="C:\Users\readmyfile.txt"set stream=##class(%Stream.FileCharacter).%New()
    set sc=stream.LinkToFile(file)
    set%stream = stream
    set%response.ContentType = ..#CONTENTTYPE
    set%fileName = file
    set%response.ContentLength=stream.Size
    return$$$OK
}
}
0
Sakthivel Perumal  Aug 16, 2023 to Ashok Kumar T

Thank you for your comment and it helps. However, still the file is not getting downloaded, instead the file is getting displayed in screen/browser along with the class name rather than original name of the file.

0
Robert Cemper  Aug 16, 2023 to Sakthivel Perumal

add this line to your method OnPreHTTP()

set %response.Headers("Content-Disposition")="attachment; filename=""your-file-name.some"""
0