2016-05-13 63 views
0

我正在寫一個自定義Springboot執行器端點,並且我想返回一個文件。但是,我找不到一種方法來返回除JSON字符串以外的任何內容。Springboot端點返回文件

我的終點就是:

import java.io.File; 
import java.net.URI; 
import org.springframework.boot.actuate.endpoint.Endpoint; 
import org.springframework.stereotype.Component; 

@Component 
public class MyEndPoint implements Endpoint<URI> { 

    @Override 
    public String getId() { 
     return "custoendpoint"; 
    } 

    @Override 
    public boolean isEnabled() { 
     return true; 
    } 

    @Override 
    public boolean isSensitive() { 
     return false; 
    } 

    @Override 
    public URI invoke() { 
     File f = new File("C:/temp/cars.csv"); 
     return f.toURI();  
    } 
} 

當我訪問本地主機:8080/custoendpoint,我收到我的文件的路徑...

任何想法?

回答

0

而不是實施Endpoint你應該實施MvcEndpoint。然後您可以訪問可以複製文件內容的HttpServletResponse。例如:

import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 

import javax.servlet.ServletException; 
import javax.servlet.http.HttpServletResponse; 

import org.springframework.boot.actuate.endpoint.Endpoint; 
import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint; 
import org.springframework.util.FileCopyUtils; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 

class CustomEndpoint implements MvcEndpoint { 

    @Override 
    public String getPath() { 
     return "/custom"; 
    } 

    @Override 
    public boolean isSensitive() { 
     return false; 
    } 

    @Override 
    public Class<? extends Endpoint<?>> getEndpointType() { 
     return null; 
    } 

    @RequestMapping(method = RequestMethod.GET) 
    public void invoke(HttpServletResponse response) 
      throws ServletException, IOException { 
     FileCopyUtils.copy(new FileInputStream(new File("c:/temp/cars.csv")), 
       response.getOutputStream()); 
    } 

}