Grails 文件下载

发布于 2024-07-10 03:19:56 字数 604 浏览 8 评论 0原文

我正在尝试创建一个允许用户上传他们喜欢的任何文件类型的网站。 我已经很好地实现了此功能,并且该文件保存在服务器上。 稍后他们可以下载该文件进行查看,但我无法使其正常工作。

我使用了我能找到的任何示例,但它们都倾向于使用文本文件作为示例。 我的问题是 pdf 和许多其他文件类型无法正确下载。 它们似乎下载得很好,但没有一个文件能够成功打开。 比较文件,似乎大部分文件内容是正确的,但某些部分不正确。

这是我的常规代码:

def file = new File(params.fileDir)    
response.setContentType("application/octet-stream")
response.setHeader("Content-disposition", "filename=${file.getName()}")
response.outputStream << file.text
return

该代码保存在由下载链接调用的控制器内。 我尝试过使用不同的 contentTypes,但我不知道哪一个可以用于任何类型 - 有吗? 我尝试的任何方法都不能解决问题。

感谢您的帮助。

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:

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

メ斷腸人バ 2024-07-17 03:19:56

问题是您使用“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

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:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文