Getting and Setting mime types.

I am attempting to do two things with the mime types.

 

Collect the mime type from a stream(%FileBinaryStream) using this syntax: myCONTENTTYPE=stream.GetAttribute("Content-Type")

However, myCONTENTTYPE always comes in empty.

Set the CONTENTTYPE PARAMETER in the OnPage ClassMethod of a ZEN page, using this syntax: s ..#CONTENTTYPE=myCONTENTTYPE

However, I cannot seem to get the correct syntax.

 

I would appreciate any and all help. Thank you.

  • 0
  • 0
  • 311
  • 3
  • 1

Answers

Files in OS by themselves do not have Content-Type attribute (streams, in web context can have Content-Type attribute). However, knowing file extension Caché has FileClassify utility method that can determine content type. Here's the wrapper I usually use:

/// Determine file mime type
/// name - full path to file
ClassMethod getFileType(name) As %String
{
    set ext = $zcvt($p(name, ".", *), "U")
    do ##class(%CSP.StreamServer).FileClassify(ext, .type , .bin, .charset)
    set ext = "/" _ ext _ "/"
    if ext = "/RTF/" {
        set type = "application/rtf"
    }
    
    return type
}

Or you can additional types into:

 set ^%SYS("CSP","MimeFileClassify", ext) = $lb(type, bin, charset)

Thank you for your reply. I am already prepared to supply mime type based on file extension. I was trying to handle the scenario when a user does not supply a file with extension...or changes the extension from correct to in-correct. Do you have any experience with changing the PARAMETER CONTENTTYPE at runtime. I believe I am using the syntax in the documentation, but Studio disagrees. Thank you again.

Do you want to serve arbitrary files?

I think you can use stream server for that:

/// Return physical file contents
/// name - full path to file
ClassMethod serve(name) As %Status
{
    #dim sc As %Status = $$$OK
    #dim %response As %CSP.Response
    //kill %request.Data
    set %request.Data("STREAMOID",1)= ##class(%CSP.StreamServer).Encrypt(##class(%CSP.StreamServer).GetOidForFile(name))
    if ##class(%CSP.StreamServer).OnPreHTTP() {
        set %response.Headers("Content-Disposition")="attachment; filename*=UTF-8''" _ ##class(%CSP.Page).EscapeURL(##class(%File).GetFilename(name), "UTF8")
        set sc = ##class(%CSP.StreamServer).OnPage()
    }

    quit sc
}

Also parameter cannot be assigned.

Comments

Just glancing comments.

You are trying to set a parameter. I'm no ZEN expert, but I am pretty sure parameters are immutable in all classes.

The other thing, if I was doing this in CSP. Setting the content-type in the OnPage method would be too late, the headers would already be written. It would have to be written before then. Not sure if ZEN is similar, but I would override the OnPreHTTP (or equivalent) and set %response.ContentType=myCONTENTTYPE in that method.