1. 程式人生 > >java web實現文件下載的註意事項

java web實現文件下載的註意事項

type ble params [] static function final filename redo

如圖,在瀏覽器中實現以下的下載方式

技術分享圖片

註意點:

1,下載文件存在於web服務器上本地上;

2,前端頁面用form形式請求。

html:

<div id="download_debit_dlg" >
    <form id="itemForm_payreslut_charge" method="post">
        <table cellspacing="5px;">
            <tr>
                <td><label for="debitDate">日期:</label></
td> <td><input type="date" name="debitDate" id="debitDate" required="required"></td> </tr> </table> </form> </div> <div id="dlg-buttons"> <a href="javascript:downloadDebitPost()"iconCls="icon-ok"
>下載</a> </div>

js:

/**
 * 
 * 開始下載
 * ctx 對應路徑
 */
function downloadDebitPost(){
    var debitDate=$(‘#debitDate‘).val();
    if (debitDate==""||debitDate==null) {
        $.messager.alert("系統提示", "請完整輸入日期");
        return;
    }
    $("#itemForm_payreslut_charge").attr("action", ctx + ‘/downloadDebit‘);
    $(
‘#itemForm_payreslut_charge‘).submit(); }

java:

@RequestMapping("/downloadDebit")
public void downloadDebit(HttpServletRequest request,HttpServletResponse response,@RequestParam Map<String, Object> reqParams) {
    String debitDate = (String) reqParams.get("debitDate");
    debitDate=debitDate.replaceAll("-", "");
    try {
        String fileName = "202210000000000001214_" + debitDate + ".txt";//文件名
        String path = "D:/file/opbill/" + fileName;//絕對路徑
        FileUploadUtil.downLoadByFilePath(request, response,path);
    } catch (BusinessException e) {
        //LOGGER.error("導出賬單出錯:", e);
    } catch (IOException e) {
        //LOGGER.error("導出賬單出錯:", e);
        e.printStackTrace();
    }
}
public class FileUploadUtil {    
    /**
     * 按文件源路徑下載文件
     * @param request
     * @param response
     * @param path
     */
    public static void downLoadByFilePath(HttpServletRequest request,
            HttpServletResponse response, String path) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            response.setContentType("text/html;charset=utf-8");
            request.setCharacterEncoding("UTF-8");
            File file = new File(path);
            if(!file.exists()){
                log.info("文件路徑:"+path);
                throw new BusinessException("下載文件路徑不存在["+path+"]");
            }
            long fileLength = file.length();
            // 編碼處理
            String fileName = path.substring(path.lastIndexOf("/") + 1);
            fileName = encodeFileName(request, fileName);
            response.setContentType("application/x-msdownload;");

            response.setHeader("Content-disposition", "attachment; filename="
                    + fileName);
            response.setHeader("Content-Length", String.valueOf(fileLength));

            bis = new BufferedInputStream(new FileInputStream(path));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (IOException e) {
            // 此異常為下載中出現的異常,不影響下載功能,可捕獲但無需拋出
        } catch (Exception e) {
            log.error("下載出現異常:", e);
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();

            }
        }
    }
}

java web實現文件下載的註意事項