簡體   English   中英

如何在 Java 中讀取多部分文件輸入流的內容

[英]How to read contents of a multipart file inputstream in Java

I have a Thymeleaf html form that accepts an uploaded file as input and then makes a post request to a Java controller for the multipart file. 然后我將文件轉換為輸入流。 雖然我能夠讀取文件的大小和輸入類型,但我無法成功打印出內容。

例如,對於一個 .doc 文件,如果我嘗試使用我找到的打印文件內容的方法,它只會打印一系列數字。 我假設是一種編碼。 是否存在打印出上傳的.doc 文件內容的方法?

我目前用來嘗試打印文件內容的 controller 操作是:

@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>

不要使用 InputStream.available()。 文檔中

使用此方法的返回值來分配用於保存此 stream 中所有數據的緩沖區永遠是不正確的。

只有從 read() 中獲得 -1 的值表示 InputStream 的結束。

例如,對於一個 .doc 文件,如果我嘗試使用我找到的打印文件內容的方法,它只會打印一系列數字。 我假設是一種編碼。

你的假設是不正確的。 A.doc 文件是復雜的二進制格式,而不僅僅是文本編碼。 (嘗試在記事本中打開 a.doc 文件。)

你得到數字是因為你在打印數字。 InputStream.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 (還有其他可用的庫;您可能需要搜索它們。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM