在Spring控制器中,如何将它们重定向到文件系统资源?

时间:2019-06-02 00:58:41

标签: spring-boot view controller

现在,这件事只是下载文件。 如果我从getFile返回filePath字符串,它会将用户发送到仅包含该文本的页面,那么浏览器将无法呈现html / png /任何我期望的那样。

我如何向用户交付文件,以便他们查看文件内容而不下载文件?

控制器:

@GetMapping(Mappings.FILES)
    public String getDirectory(Model model){

        model.addAttribute(AttributeNames.FILE_DATA, fileService.getDirectory());
        model.addAttribute(AttributeNames.FILE, new DirectoryFile());

        // debug
        for(DirectoryFile file : fileService.getDirectory()){

            System.out.println(file.getFilePath());
        }

        return ViewNames.DIRECTORY;
    }


    @PostMapping(
            value="/getfile",
            produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public @ResponseBody byte[] getFile(Model model, @ModelAttribute(AttributeNames.FILE) DirectoryFile file ){


        System.out.println("Filepath:" + file.getFilePath());


        InputStream fileIn = getClass().getResourceAsStream(file.getFilePath().trim());


        byte[] filePathBytes = file.getFilePath().trim().getBytes();

        return filePathBytes;
    }

directory.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head id="headId">
    <meta charset="UTF-8">
    <title>Title content</title>
</head>
<body>

<table>

    <tr><th>File Name</th>
    </tr>

    <tr th:each="file : ${filedata}">

        <td>

            <form action="#" th:action="@{~/home/ebay/getfile}" method="post" th:object="${filetobind}">
<!--                               th:field maps to object       -->
                <input type="text" th:field="*{filePath}" th:value="${file.filePath}" th:text="${file.filePath}"/>
                <input type="submit" value="Get" />
            </form>

        </td>

    </tr>
</table>


</body>
</html>

DirectoryFile:

package com.potatospy.httpfileserver.model;

public class DirectoryFile /*implements Serializable */{

    public static final long serialVersionUID = 1L;

    private String fileName;

    private String filePath;



    public DirectoryFile() { }

    public DirectoryFile(String fileName, String filePath) {
        this.fileName = fileName;
        this.filePath = filePath;
    }



    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }


    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }
}

FileSystemProperties:

@Component
public class FileSystemProperties {


    private File fileDirectory = new File("D:\\server\\spring\\ebayfiles\\");   // Todo This needs to be customizable ->


    public File getFileDirectory() {
        return fileDirectory;
    }

    public void setFileDirectory(File fileDirectory) {
        this.fileDirectory = fileDirectory;
    }
}

0 个答案:

没有答案