Grails 文件下载 [英] Grails File Download

查看:22
本文介绍了Grails 文件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我使用了我能掌握的任何示例,但它们都倾向于使用文本文件作为示例.我的问题是 pdf 和许多其他文件类型没有正确下载.它们似乎可以正常下载,但没有一个文件会成功打开.比较文件,似乎大部分文件内容是正确的,但某些部分不正确.

这是我的常规代码:

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

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

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.

感谢您的帮助.

推荐答案

问题是您使用file.text"将文件内容读入字符串.即使内容是二进制而不是文本(例如 PDF 文件是二进制),文件的内容也会使用系统字符编码进行转换,并使用响应编码发送到客户端,从而修改二进制内容.您应该使用不同的方法,例如:

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

这篇关于Grails 文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆