有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

spring如何在Java中读取多部分文件inputstream的内容

我有一个Thymeleaf html表单,它接受上传的文件作为输入,然后向Java控制器发出多部分文件的post请求。然后,我将该文件转换为inputstream。虽然我能够读取文件的大小和输入类型,但无法成功打印出内容

例如,对于一个。doc文件,如果我尝试打印文件内容的方法,它只打印一系列数字。我假设这是一种编码。是否存在打印已上载文件内容的方法。文件

我当前用于尝试打印文件内容的控制器操作是:

@PostMapping("/file-upload")
    public String uploadFile(@RequestParam("fileUpload") MultipartFile fileUpload, Model model) throws IOException {
        InputStream fis = fileUpload.getInputStream();

        for (int i = 0; i < fis.available(); i++) {
            System.out.println("" + fis.read());
        }

        return "home";
}

我用来提交文件的表格是:

                        <form th:action="@{/file-upload}" enctype="multipart/form-data" method="POST">
                            <div class="container">
                                <div class="row" style="margin: 1em;">
                                    <div class="col-sm-2">
                                        <label for="fileUpload">Upload a New File:</label>
                                    </div>
                                    <div class="col-sm-6">
                                        <input type="file" class="form-control-file" id="fileUpload" name="fileUpload">
                                    </div>
                                    <div class="col-sm-4">
                                        <button type="submit" class="btn btn-dark">Upload</button>
                                    </div>
                                </div>
                            </div>
                        </form>

共 (1) 个答案

  1. # 1 楼答案

    不要使用InputStream。可用()来自the documentation

    It is never correct to use the return value of this method to allocate a buffer intended to hold all data in this stream.

    从read()中仅获取值-1表示InputStream结束

    For example, for a .doc file, if I try methods I have found to print out the file's contents, it merely prints a series of numbers. Which I'm assuming is an encoding.

    你的假设是错误的。A.文档文件是复杂的二进制格式,而不仅仅是文本编码。(尝试在记事本中打开.doc文件。)

    你得到数字是因为你正在打印数字。输入流。read()返回一个int。"" + fis.read()将每个返回的int转换为字符串

    如果确实要打印文件内容,请直接写入字节:

    int b;
    while ((b = fis.read()) >= 0) {
        System.out.write(b);
    }
    

    如果您使用的是Java 9或更高版本,则只需使用:

    fis.transferTo(System.out);
    

    但是,这两个选项都不会以可读的形式显示Word文档的内容。您需要一个可以从Word文件中读取文本内容的库,如Apache POI。(还有其他可用库;您可能需要搜索它们。)