简体   繁体   English

Springboot端点返回文件

[英]Springboot endpoint to return File

I'm writting a custom Springboot Actuator Endpoint, and I would like to return a File. 我正在编写一个自定义的Springboot Actuator端点,我想返回一个文件。 However, I can't find a way to return anything else than a JSON String. 但是,除了JSON字符串,我找不到其他方法。

My Endpoint is: 我的端点是:

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

When I access localhost:8080/custoendpoint, I'm receiving the path of my file ... 当我访问localhost:8080 / custoendpoint时,我正在接收文件的路径...

Any idea ? 任何想法 ?

Rather than implementing Endpoint you should implement MvcEndpoint . 而不是实现Endpoint您应该实现MvcEndpoint You then have access to the HttpServletResponse to which you can copy the contents of the file. 然后,您可以访问HttpServletResponse ,可以将文件内容复制到其中。 For example: 例如:

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM