2010-09-16 66 views
3

我有以下代码Grails的 - 如何强制下载文件,其扩展

def fileDoc = new File(document.documentLocation); 
    if(fileDoc.exists()){ 
     // force download 
     def fileName = fileDoc.getName(); 
     response.setContentType("application/octet-stream") 
     response.setHeader "Content-disposition", "attachment; filename=${fileName}" ; 
     response.outputStream << fileDoc.newInputStream(); 
     response.outputStream.flush(); 
     return true; 
    } 

documentLocation包含字符串,如 “C:\ mydoc \ contains_some_long_string_with_id.pdf” 为例。

我希望用户下载文件,而不是从浏览器中查看它。它可以很好地工作在铬我可以下载和文件将显示“另存为”“contains_some_long_string_with_id.pdf”

但在Firefox(最新之一)..文件名是残废为“contains_some_long”只(没有pdf最后的延期)。

如何解决这个问题?该文件可以是csv,pdf,文本,html,zip,pdf或其他文件格式。

谢谢

回答

1

内容类型的字符串有可能需要蜜蜂的MIME类型您正在下载的文件。

例如。对于PDF,它可能应该是“应用程序/ pdf”

+0

但用户可以放任何格式的任何文件。它在Chrome浏览器上运行良好,但在Firefox上文件名将被损坏 – nightingale2k1 2010-09-16 07:56:42

+0

您的代码可以在下载时检查文件扩展名并设置正确的文件类型吗?我认为这可能是firefox打破扩展的原因。但我可能是错的。 – 2010-09-17 00:10:51

1

您可能有空间或特殊字符混淆Firefox。文件名应该是一个带引号的字符串:

response.setHeader "Content-disposition", "attachment; filename=\"${fileName}\""; 

RFC 2616, section 19.5.1