How can I change uploaded files directory in play

2019-04-14 11:03发布

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

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

Am I missing something?

1条回答
何必那么认真
2楼-- · 2019-04-14 11:27

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:

new line in application.conf:

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

according to the documentation sample:

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());
    }
}

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

查看更多
登录 后发表回答