如何在play 2.0.1中更改上传的文件目录? [英] How can I change uploaded files directory in play 2.0.1?

查看:132
本文介绍了如何在play 2.0.1中更改上传的文件目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的application.conf文件中指定attachments.path属性,但这没有任何效果。

I tried to specify attachments.path property in my application.conf file, but this had no effects.

在play 2.0.1的文档中,我没有'找到解释如何更改上传文件目录的任何内容。

In the documentation of play 2.0.1 I didn't find anything explaining how to change uploaded files directory.

我错过了什么?

推荐答案

虽然 application.conf 中没有这样的变量,但您可以轻松添加它并在您的方法中使用。按照您的意愿调用ie:

Although there is no such variable in application.conf you can easily add it and use in your method. Call it as you wish ie:

application.conf中的新行

myUploadPath = "/home/your-account/some/custom/upload/folder/"

根据文档示例

public static Result upload() {
    MultipartFormData body = request().body().asMultipartFormData();
    MultipartFormData.FilePart picture = body.getFile("picture");
    if (picture != null) {
        String fileName = picture.getFilename();
        String contentType = picture.getContentType();
        File file = picture.getFile();

        // added lines
        String myUploadPath = Play.application().configuration().getString("myUploadPath");
        file.renameTo(new File(myUploadPath, fileName));

        return ok("file saved as " + myUploadPath + fileName);
    } else {
        flash("error", "Missing file");
        return redirect(routes.Application.uploadform());
    }
}

使用这种方法你甚至可以执行 filename clash 重命名前检查,以防止随机覆盖。

Using this approach you can or even should perform filename clash check before renaming, to prevent random overwriting.

这篇关于如何在play 2.0.1中更改上传的文件目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆