后端和前端之间的文件(完整示例)

时间:2018-03-12 09:17:27

标签: java html spring spring-mvc docker

我正在将文件网址传递到前端。问题是url仅对服务器(settings.dockerIP())可用,因为用户没有与docker的连接。

所以我需要一种方法将我的网址转换为文件,然后将其发送给后端的所有用户..

我当前的代码是这样的(它可以工作,但用户需要一个隧道到docker主机)

控制器

 @RequestMapping("/report")
public ModelAndView report(HttpServletRequest request) {
    String environmentName = request.getParameter("name");
    ModelAndView model = new ModelAndView("report");    
    model.addObject("file", Report.getFileFromContainer(environmentName));

    return model;
}

 public static String getFileFromContainer(String environmentName) {
    Container container = getContainerID(environmentName);
    String url = "";
    if(container != null) {
        Settings settings = Settings.getSettings();
        url = "http://" + settings.getDockerIP() + ":" + settings.getDockerPort() + "/containers/" + container.getId() + "/archive?path=/path/file";
    }
    return url;
}

前端

 <a href="${file}"></a>

1 个答案:

答案 0 :(得分:1)

您可以创建一个方法,将文件作为流返回,您将此最后一个网址分配给链接按钮,

@RequestMapping(value="getFile", method=RequestMethod.GET)
public void getFile(HttpServletResponse response,HttpServletRequest request) {
     String environmentName = request.getParameter("name");
    //here the code to get your file as stream 
    //whether getting the file by Ressource or buffred ,
    //here for example I named a getfileStream() method wihch return your file  InputStream
    InputStream myStream  = getFileStream(environmentName);


    // Set the content type and attachment header add filename and it's extention.
    response.addHeader("Content-disposition", "attachment;filename=myfile.myExtention");
    response.setContentType("txt/plain");

    // copy your file stream to Response 
    IOUtils.copy(myStream, response.getOutputStream());
    response.flushBuffer();
}

要获取名称parameter,您只需将其传递给modelview控制器中的/report,然后将其分配给您的链接。

如下:

@RequestMapping("/report")
public ModelAndView report(HttpServletRequest request) {
    String environmentName = request.getParameter("name");
    ModelAndView model = new ModelAndView("report");    
    model.addObject("name", environmentName);

    return model;
}

然后您的链接就像:

<a href="<c:url value="/getFile" />?name=${name}">Get file</a>

getFileStream可能就像:

public InputStream getFileStream(String environmentName) {
    Container container = getContainerID(environmentName);
    String url = "";
    if(container != null) {
        Settings settings = Settings.getSettings();
        url = "http://" + settings.getDockerIP() + ":" + settings.getDockerPort() + "/containers/" + container.getId() + "/archive?path=/path/file";
    }
    InputStream is = new URL(url).openStream();

    return is; 
}

您必须在项目中添加以下appace common io才能使用IOUtils

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>