Springboot端点返回文件
问题描述:
我正在写一个自定义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,我收到我的文件的路径...
任何想法?
答
而不是实施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());
}
}