Scala Lift - 将上传的文件保存到服务器目录

时间:2012-02-20 12:34:45

标签: file scala lift

我目前正在我的Lift项目的webapp文件夹中存储图像,我知道这将导致将来出现问题。

val path = "src/main/webapp/files/"

我用来保存它的代码:

case Full(file) => 

    val holder = new File(path, "test.txt")
    val output = new FileOutputStream(holder)               

    try { 

        output.write(file) 

    } finally { 

        output.close() 

    }

}

我要做的是将服务器根保存在一个名为files的易于管理的文件夹中,以便在项目文件夹之外的SERVER_ROOT /文件。

首先,我如何访问服务器根目录的路径,以便将其保存在那里?

其次我如何从我的应用程序提供这些文件,以便我可以在页面上显示它们?

在此先感谢,任何帮助非常感谢:)

1 个答案:

答案 0 :(得分:2)

您必须根据绝对路径将文件存储到文件系统上的确切位置。我写了这段代码并且它有效,所以它可以帮助你:

def storeFile (file : FileParamHolder): Box[File] = 
  {
    getBaseApplicationPath match
        {
            case Full(appBasePath) =>
            {
                var uploadDir = new File(appBasePath + "RELATIVE PATH TO YOUR UPLOAD DIR")
                val uploadingFile = new File(uploadDir, file.fileName)

                println("upload file to: " + uploadingFile.getAbsolutePath)

                var output = new FileOutputStream(uploadingFile)
                try
                { 
                    output.write(file.file)
                }
                catch 
                { 
                    case e => println(e) 
                }
                finally
                { 
                    output.close
                    output = null
                }

                Full(uploadingFile)
            }
            case _ => Empty
        }
  }

这是我的getBaseApplicationPath函数,它找出本地机器(服务器或你的开发PC)的绝对路径:

def getBaseApplicationPath: Box[String] = 
    {
        LiftRules.context match
        {
            case context: HTTPServletContext => 
            {
                var baseApp: String = context.ctx.getRealPath("/")

                if(!baseApp.endsWith(File.separator))
                    baseApp = baseApp + File.separator

                Full(baseApp)
            }
            case _ => Empty
        }
    }