Route to static file in Play! 2.0

后端 未结 9 1750
甜味超标
甜味超标 2021-01-30 14:05

I\'m trying to make a route to a specific static file but everything I\'m trying ends with an error.

I\'ve made 3 different attempts:

1.

GET /fil         


        
9条回答
  •  -上瘾入骨i
    2021-01-30 14:18

    Play java packages public folder in a jar file and this would be a problem if you would like to serve a static file that resolves to an absolute file location in the server. The right way to do is to have your own controller and use it to serve the static file.

    For ex, to serve a file "mystatic.html" that is in the

    
        |-----
            |------mystatic.html
    

    You would configure this route in your routes file.

    GET /mystatic           mypackage.mycontrollers.Static.getFile(path="/myfolder/mystatic.html")
    

    and your controller would be implemented as follows.

    package mypackage.mycontroller;
    
    import java.io.File;
    import com.google.inject.Inject;
    import com.google.inject.Provider;
    
    import play.Application;
    import play.mvc.Controller;
    import play.mvc.Result;
    import play.mvc.Results;
    
    public class Static extends Controller {
    
        @Inject
        Provider app;
    
        public Result getFile(String path){
            File file = app.get().getFile(path);
            if(file.exists()){
                return ok(file);            
            }else{
                return Results.notFound();
            }
        }   
    }
    

提交回复
热议问题