Oracle + Ibatis使用Blob二進制進行下載和使用文件流進行下載

數據庫:使用BLOB存放二進制流,BLOB轉換爲java類型爲byte[]

DECLARE
    CNT INTEGER;
BEGIN
    SELECT COUNT(0) INTO CNT FROM USER_ALL_TABLES
    WHERE TABLE_NAME = UPPER('G_ATTACH_BYTE');
    IF CNT = 0 THEN
    EXECUTE IMMEDIATE 'CREATE TABLE G_ATTACH_BYTE(
        BYTE_ID NUMBER,
        ATTACH_ID NUMBER,
        ATTACH_BYTE BLOB
        )';
    END IF;
END;
/

COMMENT ON TABLE G_ATTACH_BYTE IS '文件存儲表'
/

COMMENT ON COLUMN G_ATTACH_BYTE.BYTE_ID IS '主鍵'
/
COMMENT ON COLUMN G_ATTACH_BYTE.ATTACH_ID IS '附件Id'
/
COMMENT ON COLUMN G_ATTACH_BYTE.ATTACH_BYTE IS '二進制文件'
/

DECLARE
    CNT INTEGER;
BEGIN
    SELECT COUNT(0) INTO CNT FROM USER_CONSTRAINTS
    WHERE CONSTRAINT_NAME = UPPER('G_ATTACH_BYTE_PK');
    IF CNT = 0 THEN
    EXECUTE IMMEDIATE 'ALTER TABLE G_ATTACH_BYTE ADD CONSTRAINT G_ATTACH_BYTE_PK PRIMARY KEY(BYTE_ID)';
    END IF;
END;
/

1.保存文件,和普通的一樣,javaBean中一個字段類型爲byte[]

    /**
     * @Description:保存一份數據備份到byte表
     * @param attachId
     * @param filePath
     * @author luhao
     * @since:2019年5月29日 下午2:21:30
     */
    private void saveAttachByte(Integer attachId,String filePath) {
        byte[] bytes = null;
        try {
            bytes = IOUtil.toByteArray(new FileInputStream(filePath));
        } catch (FileNotFoundException e) {
            logger.info(filePath + "未讀取到文件!");
        } catch (IOException e) {
            logger.info("IO錯誤:attachId = " + attachId + ",filePath = " + filePath);
        }
        
        AttachByte attachByte = new AttachByte();
        attachByte.setAttachId(attachId);
        attachByte.setAttachByte(bytes);
        
        getDaoFacade().getAttachDao().saveAttachByte(attachByte);
    }

    <!-- 新增文件存儲表 -->
    <insert id="saveAttachByte" parameterClass="com.nstc.aims.model.AttachByte">
        <selectKey resultClass="java.lang.Integer" keyProperty="byteId">
            SELECT SEQ_G_ATTACH_BYTE.NEXTVAL AS byteId FROM DUAL
        </selectKey>
        INSERT INTO G_ATTACH_BYTE (
            BYTE_ID,
            ATTACH_ID,
            ATTACH_BYTE
        ) VALUES(
            #byteId#,
            #attachId#,
            #attachByte#
        )
    </insert>

public class AttachByte {
    
    /** 主鍵 */
    private Integer byteId;
    
    /** 附件Id */
    private Integer attachId;
    
    /** 二進制文件 */
    private byte[] attachByte;
}

二、讀取和下載


    /**
     * @Description:從數據庫下載文件
     * @param request
     * @author luhao
     * @since:2019年5月30日 上午9:50:03
     */
    private void downloadByDB(RequestContext request) {
        HttpServletResponse response = (HttpServletResponse) ContextUtils.getHttpContext().getResponse();

        String fileId = request.getParameter("fileId");
        Integer attachId = CastUtil.toInteger(fileId,0);
        
        ServerLocator locator = (ServerLocator) FrameworkUtil.getServiceLocator("AIMS");
        AttachByteView attachByte = locator.getAttachService().getAttachByteByAttachId(attachId);
        
        if (attachByte != null && attachByte.getAttachByte() != null) {
            byte[] bytes = attachByte.getAttachByte();
            String fileName = attachByte.getAttachName();
            OutputStream outputStream = null;
            response.reset();
            response.setContentType("application/x-msdownload");
            response.setHeader("Content_Length",String.valueOf(bytes.length));
            try {
                response.setHeader("Content-disposition",
                        "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8").replace('+', ' '));
                outputStream = response.getOutputStream();
                outputStream.write(bytes);
                outputStream.flush();
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage());
            } finally {
                if(outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e.getMessage());
                    }
                }
            }
        }        
    }

三、使用普通文件流下載,別人的方法參考

 // 下載附件
    private void download(RequestContext request) throws Exception {
        HttpServletResponse response = (HttpServletResponse) ContextUtils.getHttpContext().getResponse();
        /**
         * update by zengshaoqi 2019/1/14 13:48
         * TA0700 添加非明細導入excel動態下載
         */
        String downloadHandler = request.getParameter("downloadHandler");
        if (CastUtil.toNotEmptyString(downloadHandler) != null) {
            downloadByHandler(request, response);
            return;
        }

        String fileId = request.getParameter("fileId");
        String flag = request.getParameter("flag");// 是合作金融網點登記的附件1:是
        String apply = request.getParameter("isApply");

        String fileName = null;
        String filePath = null;
        try {
            ServerLocator locator = (ServerLocator) FrameworkUtil
                    .getServiceLocator("AIMS");
            if (ASS_FILE.equals(flag)) {
                AssociateBankAttach assFile = locator.getAssociateBankService()
                        .queryAssociateBankAttachByFileId(
                                CastUtil.toInteger(fileId));
                fileName = assFile.getFileName();
                filePath = assFile.getFilePath();
            } 
            //N0801 增加對正式附件的下載 start
            else if(ATTACH_FILE.equals(flag)) {
                Attach attach = locator.getAttachService().getAttachById(fileId);
                fileName = attach.getAttachName();
                filePath = attach.getFilePath();
            }else if(UM_FILE.equals(flag)) {
                UmFmAttach umFmAttach = locator.getUmFormService().queryUmFmAttachByFileId(CastUtil.toInteger(fileId));
                fileName = umFmAttach.getFileTitle();
                filePath = umFmAttach.getFileName();
            }
            
            //N0801 增加對正式附件的下載 end
            
            else {
                if ("true".equals(apply)) {
                    UmFmAttach file = locator
                            .getUmFormService()
                            .queryUmFmAttachByFileId(CastUtil.toInteger(fileId));
                    fileName = file.getFileTitle();
                    filePath = file.getFileName();
                } else {
                    AIMSFile aimsFile = locator.getCommonService()
                            .queryAimsFileById(CastUtil.toInteger(fileId));
                    fileName = aimsFile.getFileName();
                    filePath = aimsFile.getFilePath();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        if (fileName != null && filePath != null) {
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                File file = new File(filePath);
                if (!file.exists()) {
                    throw new RuntimeException("資料文件“" + fileName + "”不存在!");
                }
                response.reset();
                response.setContentType("application/x-msdownload");
                response.setHeader(
                        "Content-disposition",
                        "attachment; filename="
                                + java.net.URLEncoder.encode(fileName, "UTF-8")
                                .replace('+', ' '));
                response.setHeader("Content_Length",
                        String.valueOf(file.length()));
                inputStream = new FileInputStream(file);
                outputStream = response.getOutputStream();
                byte[] buff = new byte[2048];
                int bytesRead = 0;
                while ((bytesRead = inputStream.read(buff, 0, buff.length)) > 0) {
                    outputStream.write(buff, 0, bytesRead);
                }
                outputStream.flush();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage());
            } finally {
                if (inputStream != null)
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        throw new RuntimeException(e.getMessage());
                    }
                if (outputStream != null)
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        throw new RuntimeException(e.getMessage());
                    }
            }
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章