spring Grails 文件下载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/396677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Grails File Download
提问by James Camfield
I'm trying to craete a site which allows users to upload any file type they like. I've implemented this feature fine, and the file is held on the server. Later on they can download the file to view, but i'm having trouble getting it to work.
I've used any examples I can get hold of but they all tend to use text files as examples. My problem is that pdf's and many other file types aren't downloading properly. They seem to download fine, but none of the files will open successfully. Comparing the files, it seems most of the files content is correct, but certain parts are not.
Here's my groovy code:
我正在尝试创建一个允许用户上传他们喜欢的任何文件类型的站点。我已经很好地实现了这个功能,并且文件保存在服务器上。稍后他们可以下载文件进行查看,但我无法使用它。
我使用了我能掌握的任何示例,但它们都倾向于使用文本文件作为示例。我的问题是 pdf 和许多其他文件类型没有正确下载。它们似乎可以正常下载,但没有一个文件会成功打开。比较文件,似乎大部分文件内容是正确的,但某些部分不是。
这是我的常规代码:
def file = new File(params.fileDir)
response.setContentType("application/octet-stream")
response.setHeader("Content-disposition", "filename=${file.getName()}")
response.outputStream << file.text
return
This code is held inside a controller which is called by a download link. I've tried playing around with different contentTypes, but I don't know which I could use for any type - is there one? Anything I try doesn't solve the problem.
此代码保存在由下载链接调用的控制器中。我尝试过使用不同的内容类型,但我不知道我可以将哪种类型用于任何类型 - 有吗?我尝试的任何事情都不能解决问题。
Thanks for your help.
谢谢你的帮助。
回答by Siegfried Puchbauer
The problem is that you read the content of the file into a String by using "file.text". The content of the file is converted with the system character encoding even if the content is binary, not text (eg. PDF files are binary) and sent to the client using the response encoding and thereby modifing the binary content. You should rather use a different approach like this:
问题是您使用“file.text”将文件内容读入字符串。即使内容是二进制而不是文本(例如 PDF 文件是二进制),文件的内容也会使用系统字符编码进行转换,并使用响应编码发送到客户端,从而修改二进制内容。您应该使用不同的方法,如下所示:
def file = new File(params.fileDir)
response.setContentType("application/octet-stream")
response.setHeader("Content-disposition", "attachment;filename=${file.getName()}")
response.outputStream << file.newInputStream() // Performing a binary stream copy

