Grails文件下载 [英] Grails File Download

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

问题描述

我正在尝试一个网站,允许用户上传他们喜欢的任何文件类型。我已经实现了这个功能,文件被保存在服务器上。后来他们可以下载文件来查看,但是我遇到麻烦让它工作。



我使用任何可以抓住的例子,但他们都倾向于使用文本文件作为例子。我的问题是,pdf和许多其他文件类型没有正确下载。他们似乎下载得很好,但没有一个文件会成功打开。比较文件,似乎大多数文件内容是正确的,但某些部分不是。


这是我的groovy代码:

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

此代码保存在由下载程序调用的控制器内链接。
我试过玩过不同的contentTypes,但我不知道我可以使用什么类型 - 有一个吗?感谢您的帮助。

解决方案


$ b

问题是使用file.text将文件的内容读入String。即使内容是二进制文件,也不是文本(例如,PDF文件是二进制文件),文件的内容被转换为系统字符编码,并使用响应编码发送给客户端,从而修改二进制内容。你应该使用这样一种不同的方法:

  def file = new File(params.fileDir)
response。 setContentType(application / octet-stream)
response.setHeader(Content-disposition,attachment; filename = $ {file.getName()})

response.outputStream << file.newInputStream()//执行二进制流副本


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.

解决方案

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天全站免登陆