簡體   English   中英

在Java中保存多個附件

[英]save multiple attachments in java

我已經將一個文件保存到數據庫中(postgresql),並且工作正常。 但是當我嘗試上傳多個文件時,我陷入了困境。

我的jsp文件上傳:

<input type="file" id="reqFile" name="attachments.myFile" multiple/>

這是我的操作方法:

    public String SaveAttachments() throws SQLException, IOException {
    int case_id = (Integer) session.get("case_id");
    System.out.println("in save attachments()");
    int uploaded_by = 1;
    try {
        File destFile = new File(attachments.getMyFileFileName());
        FileUtils.copyFile(attachments.getMyFile(), destFile);
        fis = new FileInputStream(destFile);
        currentCon = ConnectionManager.getConnection();
        pstmt = (PreparedStatement) currentCon.prepareStatement("insert into case_attachments(case_id, attachment, attachment_title, upload_date, uploaded_by) values(?,?,?,current_date,?)");
        pstmt.setInt(1, case_id);
        pstmt.setBinaryStream(2, fis, (int) destFile.length());
        pstmt.setString(3, attachments.getMyFileFileName());
        pstmt.setInt(4, uploaded_by);
        pstmt.executeUpdate();
    } catch (Exception e) {
        System.out.println("Error From SaveAttachments :" + e);
    }
    return SUCCESS;
}

當我附加多個文件時,它將以逗號分隔的格式進入數據庫的同一列。 用戶附加多個文件時,如何保存文件在不同的行中? 提前致謝。

您可以按此處所述上傳多個文件 ,然后只需要循環將它們一次插入到數據庫中即可。

您只需要確定是使用業務層還是直接從Action中執行插入工作(不是最佳實踐...),以及是否將所有文件放在單個事務中或將每個文件放在一個事務中即可。

請記住,HTML5的multiple屬性應為multiple="multiple" ,而不僅僅是multiple (盡管大多數瀏覽器即使“ quirk”也會正確處理它)。

使用數組進行多次上傳。

<td><input type="file" name="file[]" class="multi" id="reqFile"></td>

暫無
暫無

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

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