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

标签 grails

我有一个Web应用程序,可将文件上传到文件系统并在列表中显示它们。我试图用一个按钮删除该项目。我知道我需要获取目录文件的路径才能删除它,并且我认为这是我的问题所在:

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

最佳答案

我认为您在此行中有一个错误:

  def path = Document.get(path.id)

您尝试从您刚刚声明的path变量获取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()
      }
 }

然后您可以在 Controller 中执行以下操作:
def delete = {

    def doc = Document.get(params.id)

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

    redirect( action:'list' )
}

关于grails - 尝试从目录文件系统中删除上载的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29704754/

相关文章:

performance - Grails 性能 : XML processing 4x slower in tomcat than run-app?

mongodb - Grails、Spring Security 和 Mongo

unit-testing - 在Grails单元测试中模拟动态查找器

unit-testing - 在save()上的Grails 2.4.4 Controller 测试返回空模型

html - Grails response.sendError 不渲染 gsp 标签

grails - 定义所有域类的默认ID类型

grails - 如何在 Grails 中隐藏 URL 参数

validation - 如何添加验证以限制正在创建的行数

如果在添加关系后调用 Grails save() 不会保存

hibernate - 如何创建返回 grails 标准方法闭包的自定义函数