尝试从目录文件系统中删除上载的文件

时间:2015-04-17 16:30:11

标签: grails

我有一个网络应用程序,可以将文件上传到文件系统并在列表中显示它们。我想用一个按钮删除该项目。我知道我需要获取目录文件的路径才能删除它,我相信这就是我被困住的地方:

def delete = {

    def doc = Document.get(params.id)
    def path = Document.get(path.id)

    doc.delete(path)

    redirect( action:'list' )
}

我收到的错误:No such property: path for class: file_down.DocumentController Possible solutions: flash

在我看来def path = Document.get(path.id)是错误的,在这种情况下我们如何找到文档的路径?

这是我的上传方法,我上传文件,将其分配给特定的文件大小,日期和fullPath(这是上传的文件夹)

def upload() {
    def file = request.getFile('file')
    if(file.empty) {
        flash.message = "File cannot be empty"
    } else {
        def documentInstance = new Document()
        documentInstance.filename = file.originalFilename
        documentInstance.fullPath = grailsApplication.config.uploadFolder + documentInstance.filename
        documentInstance.fileSize = file.getSize() / (1024 * 1024)
        documentInstance.company = Company.findByName(params.company)
        if (documentInstance.company == null) {
            flash.message = "Company doesn't exist"
            redirect (action: 'admin')
        }
        else {
            file.transferTo(new File(documentInstance.fullPath))
            documentInstance.save()
            redirect (action:'list', params: ['company': params.company])
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我认为你在这一行中有错误:

  def path = Document.get(path.id)

您尝试从刚才声明的路径变量中获取path.id.

我很确定你的意思是

 def path = new File(doc.fullPath)

 path.delete() // Remove the file from the file-system

 doc.delete() // Remote the domain instance in DB

替代:

 class Document {
      // Add this to your Document domain
      def beforeDelete = {
            new File(fullPath).delete()
      }
 }

然后你可以在控制器中执行此操作:

def delete = {

    def doc = Document.get(params.id)

    doc.delete() // Delete the domain instance in DB

    redirect( action:'list' )
}