天天看點

java從linux伺服器下載下傳檔案

java從linux伺服器下載下傳檔案到本地

最近做項目,使用的技術較老,前端用的架構是jsp,主要技術是jquery、js、css、html等,後端用到的主要是springmvc、存儲過程等。

下面是一個檔案下載下傳的簡單實作。主要是客戶在浏覽器點選一個pdf檔案,進行下載下傳。改檔案存在于公司的伺服器上。

一、前端代碼

1、html代碼

<div class="border-gb-title">項目檔案</div>
    <div class="grey-card jus-c ptb30 flex">
        <div class="tc mlr50 cupointer" onclick="getProjectFiles(1)"><img src="/res/images/file.png">
            <div class="mt5 fs16">合同</div>
        </div>
        <div class="tc mlr50 cupointer" onclick="getProjectFiles(2)"><img src="/res/images/file.png">
            <div class="mt5 fs16">計劃說明書</div>
        </div>
        <div class="tc mlr50 cupointer" onclick="getProjectFiles(3)"><img src="/res/images/file.png">
            <div class="mt5 fs16">風險說明書</div>
        </div>
        <div class="tc mlr50 cupointer" onclick="getProjectFiles(6)"><img src="/res/images/file.png">
            <div class="mt5 fs16">服務協定</div>
        </div>
    </div>
           

2、js代碼

//擷取檔案,主要是從資料庫擷取到:檔案名、檔案路徑
    function getProjectFiles(type) {
        var fileParam = {
            pageNo: 1,
            pageSize: 10,
            xmId: ${detail[0]["項目ID"]},
            cxlx: type,
        };
        $.ajax({
            url: "/prod/getProjectFiles",
            type: "POST",
            data: fileParam,
            dataType: "JSON",
            success: function (ret) {
                if (ret && ret['code'] > 0) {
                    debugger
                    //渲染界面
                    var dataList = ret['list'];
                    download(dataList[0]["附件名"],dataList[0]["附件路徑"]);
                }
            }
        })
    }
//下載下傳檔案,調用後端接口
    function download(fileName,filePath){
        window.open("/downloadTwo?fileName="+encodeURI(fileName)+"&downUrl="+filePath);
        return ;
    }
           

3、css樣式

前端的所有樣式都是使用layui架構的。

二、背景代碼

1、擷取檔案

主要是,調用存儲過程,去資料庫擷取檔案名和檔案路徑,後面用于下載下傳。

/**
     * 擷取項目檔案
     *   I_CXLX       IN NUMBER, --查詢類型 1|信托合同 2|信托計劃說明書3|認購風險說明書 5|隐私協定|6使用者服務協定
     *   I_XSXM      IN NUMBER --發行方案id
     * @param request
     * @param response
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/getProjectFiles",method = RequestMethod.POST)
    @ResponseBody
    public DataResultSet getProjectFiles(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap){
        int pageNo = ParamUtils.getInt(request, "pageNo", 1); // 頁碼
        int pageSize = ParamUtils.getInt(request, "pageSize", 10); // 取得顯示條數
        String cxlx = ParamUtils.getString(request, "cxlx", ""); // 查查詢類型 1|信托合同 2|信托計劃說明書3|認購風險說明書 5|隐私協定|6使用者服務協定
        String xmId = ParamUtils.getString(request, "xmId", ""); //發行方案id
        DataResultSet productHistory = prodService.getProjectFiles(pageNo,pageSize,cxlx,xmId);
        return productHistory;
    }
           

2、開始下載下傳

/**
     * 附件下載下傳
     *
     * @param request
     * @param response
     */
    @RequestMapping("/downloadTwo")
    public void downloadFileTwo( HttpServletRequest request, HttpServletResponse response) {

        String fileName = request.getParameter("fileName");
        String downUrl = request.getParameter("downUrl");
        goToDownload(request, response, downUrl, fileName);

    }

    /**
     * 下載下傳
     *
     * @param request
     * @param response
     * @param downUrl  下載下傳的路徑
     * @param fjmc     下載下傳檔案的名稱
     */
    private void goToDownload(HttpServletRequest request, HttpServletResponse response, String downUrl, String fjmc) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/x-msdownload");
        try {
            String encodenickname = URLEncoder.encode(fjmc,"UTF-8");//轉Unicode不然ie會亂碼
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(encodenickname.getBytes("UTF-8"), "ISO8859-1"));
            //這裡注掉的代碼是本地測試的
//            String path = request.getSession().getServletContext().getRealPath("/");
//            String ATTACH_PATH= AppConfig.getInstance().getProperty("attach.base","");
//            if (StringUtils.isNotEmpty(ATTACH_PATH)) {
//                path = ATTACH_PATH;
//            }
//            logger.debug("=path===" + path);
            File file = new File( downUrl);
            if (!file.exists()) {
                response.sendError(404, "File not found!");
                return;
            }
            long fileLength = file.length();
            response.setHeader("Content-Length", String.valueOf(fileLength));
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            BufferedOutputStream 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);
            }
            bis.close();
            bos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

           

三、效果

java從linux伺服器下載下傳檔案

直接點選檔案圖檔或者檔案,就可以下載下傳。

java從linux伺服器下載下傳檔案
上面測試,是在谷歌浏覽器,火狐,IE也測試過了,親測有效。