如何在Grails中保存到文件系统目录
我正在尝试将上载的文件保存到文件系统目录中,并允许其他用户下载它 我目前正在将其保存在数据库中,而不是文件系统目录中。这是我的密码:如何在Grails中保存到文件系统目录,grails,file-upload,Grails,File Upload,我正在尝试将上载的文件保存到文件系统目录中,并允许其他用户下载它 我目前正在将其保存在数据库中,而不是文件系统目录中。这是我的密码: class Document { String filename byte[] filedata Date uploadDate = new Date() static constraints = { filename(blank: false, nullable:false)
class Document {
String filename
byte[] filedata
Date uploadDate = new Date()
static constraints = {
filename(blank: false, nullable:false)
filedata(blank: true, nullable: true, maxSize:1073741824)
}
}
我上传文件的控制器是:
class DocumentController {
static allowedMethods = [delete: "POST"]
def index = {
redirect(action: "list", params: params)
}
def list() {
params.max = 10
[documentInstanceList: Document.list(params), documentInstanceTotal: Document.count()]
}
def uploadPage() {
}
def upload() {
def file = request.getFile('file')
if(file.isEmpty())
{
flash.message = "File cannot be empty"
}
else
{
def documentInstance = new Document()
documentInstance.filename = file.getOriginalFilename()
documentInstance.filedata = file.getBytes()
documentInstance.save()
}
redirect (action: 'list')
}
}
我想你可以做一个类似下面的功能:
boolean upload(MultipartFile uploadFile, String fileUploadDir){
String uploadDir = !fileUploadDir.equals('') ?: 'C:/temp' //You define the path where the file will be saved
File newFile = new File("$uploadDir/${uploadFile.originalFilename}"); //You create the destination file
uploadFile.transferTo(newFile); //Transfer the data
/**You would need to create an independent Domain where to store the path of the file or have the path directly in your domain*/
}
因为您只需要保存文件的路径,所以可以向域中添加字符串来存储它,也可以创建一个独立的域来存储文件的数据。您还需要在需要的地方添加try/catch语句
要检索文件,您需要向控制器中添加以下代码:
File downloadFile = new File(yourFileDomain?.pathProperty) //get the file using the data you saved in your domain
if(downloadFile){ //Set your response properties
response.characterEncoding = "UTF-8"
response.setHeader "Content-disposition", "attachment; filename=\"${yourFileDomain?.fileNameProperty}\"" //add the header with the filename you saved in your domain you could also set a default filename
//response.setHeader "Content-disposition", "attachment; filename=\"myfile.txt\""
response.outputStream << new FileInputStream(downloadFile)
response.outputStream.flush()
return
}
File downloadFile=new File(yourFileDomain?.pathProperty)//使用保存在域中的数据获取文件
if(downloadFile){//设置响应属性
response.characterEncoding=“UTF-8”
response.setHeader“Content disposition”,“attachment;filename=\”${yourFileDomain?.fileNameProperty}\\\//使用保存在域中的文件名添加标题您还可以设置默认文件名
//response.setHeader“内容处置”,“附件;文件名=\“myfile.txt”
response.outputStream您是否在服务器端生成原始文件名以避免文件系统命名冲突?@Alexjjsmith,在我的实际控制器中,我使用随机UUI和原始文件扩展名保存文件,从而避免存储文件的服务器中的文件名冲突。它还允许我将所有文件放在一个或多个文件中如有必要,我还存储原始文件名以将文件及其原始文件名返回给用户。