【问题标题】:How do I get the file name from HTTP header while downloading a file with Grails rest plugin?使用 Grails REST 插件下载文件时如何从 HTTP 标头获取文件名?
【发布时间】:2015-08-07 12:41:51
【问题描述】:

我正在使用 Grails Rest 插件从服务器下载文件,但如何获取作为 http 标头字段“Content-disposition”一部分的建议文件名?

我的代码:

withHttp(uri:uri){
   def logo = new Logo()
   def status = get(path:path, query:[identity: identity]){ resp, body ->
       if( resp.status == 200){
           logo.contentType = resp.contentType
           // logo.fileName =  How?
           logo.bytes = body.getBytes()
       }
       return resp.status
   }
   if(status == 200){
       return logo
   }
   else{
       log.warn("Failed to fetch logo ")
       return null;
   }
}

我可以读取内容类型,如何获得建议的文件名?

【问题讨论】:

    标签: rest http grails


    【解决方案1】:

    嗯,我想出了一种方法。也许不是最好的解决方案,但它适用于最常见的场景。

    编辑:我已更改此代码以使用现有方法来解析标头值的元素和属性。希望它能更好地处理不同的标题场景。我仍然不确定 *filename 参数是否被正确处理。

    withHttp(uri:uri){
       def logo = new Logo()
       def status = get(path:path, query:[identity: identity]){ resp, body ->
           if( resp.status == 200){
               logo.contentType = resp.contentType
               def contentDisposition = resp.getFirstHeader('Content-Disposition')
               def element = contentDisposition?.elements.find{ it.name.equalsIgnoreCase('filename') || it.getParameterByName('filename')}
               if(element)
                   logo.fileName = element.getParameterByName('filename')?.value ?: element.value  
               logo.bytes = body.getBytes()
           }
           return resp.status
       }
       if(status == 200){
           return logo
       }
       else{
           log.warn("Failed to fetch logo ")
           return null;
       }
    }
    

    【讨论】:

    • 好吧,这段代码会因为许多有效的字段值而中断。请参阅 RFC 6266。
    • 确实如此。它不处理文件名* 参数或包含转义引号的文件名。它对我有用,因为我在受控环境中使用它。我将对此添加注释。如果您有答案,请发布更好的答案。
    • 我已经更改了上面的代码。 Hopefylly 它可以更好地处理 RFC。在我至少获得一张赞成票之前,我不会接受自己的回答。也许有人有更好的解决方案?
    猜你喜欢
    • 2015-04-11
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 2011-07-08
    • 1970-01-01
    • 2015-07-07
    • 2016-01-07
    相关资源
    最近更新 更多