Question
· 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=1
    Set %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
Discussion (4)1
Log in or sign up to continue

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 file
    set 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
}
}