How to save to a file system directory in Grails

2020-08-08 05:09发布

问题:

I am trying to save an uploaded file into the file system directory, and allow other users to download it.

I am currently saving it in my database and not in my file system directory. Here is my code:

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

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

and my controller for uploading the file is:

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')
    }
}

回答1:

I think you could do a fuction similar to the one below:

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*/

}

Since you will only need to save the path of the file you could add a string to your domain to store it or you could create an independent domain to store the data of your file. You will also need to add try/catch statements where needed.

And to retrieve the file you would need to add to your controller something like the next code:

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
        }

Hope this helps, any comments are welcome.