gpt4 book ai didi

grails - 如何在Grails中保存到文件系统目录

转载 作者:行者123 更新时间:2023-12-02 15:05:58 25 4
gpt4 key购买 nike

我正在尝试将上传的文件保存到文件系统目录中,并允许其他用户下载它。

我当前将其保存在数据库中,而不是文件系统目录中。这是我的代码:

class Document {
String filename
byte[] filedata
Date uploadDate = new Date()

static constraints = {
filename(blank: false, nullable:false)
filedata(blank: true, nullable: true, maxSize:1073741824)
}
}

我上传文件的 Controller 是:
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语句。

为了检索文件,您需要将类似下代码的内容添加到 Controller 中:
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
}

希望对您有所帮助,欢迎提出任何意见。

关于grails - 如何在Grails中保存到文件系统目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29310352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com