1. 程式人生 > >java 後臺掛載apk檔案供前端下載

java 後臺掛載apk檔案供前端下載

/**
     * App下載介面,以位元組流的形式返回apk
     */
    @RequestMapping("/download")
    @ResponseBody
    public void appDownLoad(HttpServletRequest request,HttpServletResponse response) {
        PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("taskcare-appversion.properties");
        String path = propertiesUtil.getKey("appversion.upladPath");
        String apkName = propertiesUtil.getKey("appdownload.androidName");//apk的名字
        String apkPath = path+"/"+apkName;//apk的path

        //new 一個apk的檔案物件
        File file = new File(apkPath);
        try {
        if(file.exists()){
            // 以流的形式下載檔案。

            //先以輸入流把檔案輸入到buffer中,再以輸出流的形式輸出
            InputStream fis = new BufferedInputStream(new FileInputStream(apkPath));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 設定response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        }
        }catch(Exception e) {
            System.out.println("下載檔案錯誤"+e.getMessage());
        }
    }