【问题标题】:Springboot endpoint to return FileSpring Boot 端点返回文件
【发布时间】:2016-05-13 12:51:11
【问题描述】:

我正在编写一个自定义 Springboot Actuator Endpoint,我想返回一个 File。但是,我找不到返回 JSON 字符串以外的任何内容的方法。

我的端点是:

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

当我访问 localhost:8080/custoendpoint 时,我正在接收我的文件的路径...

有什么想法吗?

【问题讨论】:

    标签: java spring-boot spring-boot-actuator


    【解决方案1】:

    您应该实现MvcEndpoint,而不是实现Endpoint。然后您可以访问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());
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2019-04-02
      • 2020-02-18
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 2020-10-26
      • 2014-04-07
      • 2021-06-13
      • 2018-10-31
      相关资源
      最近更新 更多