1. 程式人生 > >把response body以流的形式下載檔案

把response body以流的形式下載檔案

 @GetMapping("downProcessFile.do")
    @ApiOperation(value = "test匯出", tags = {"productAccess"}, httpMethod = "GET")
    public void downProcessFile(HttpServletRequest request, HttpServletResponse response) {
        String url = "http://fsmartbucket-30011.sz.gfp.tencent-cloud.com/123aa21088d846d8931cb463defd6694xlsx
"; String url2="http://fsmartbucket-30011.sz.gfp.tencent-cloud.com/123aa21088d846d8931cb463defd6694xlsx"; try { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url2); HttpResponse httpResponse = httpClient.execute(httpGet); int ret = httpResponse.getStatusLine().getStatusCode(); long contentLength = httpResponse.getEntity().getContentLength(); InputStream fis = httpResponse.getEntity().getContent(); *//* BufferedReader br = new BufferedReader(new InputStreamReader(is)); StringBuffer sb = new StringBuffer();*//* // File file = new File(path); // String filename = file.getName();// 獲取日誌檔名稱 String filename = "abc.xlsx"; // fis = new BufferedInputStream(new FileInputStream(path)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); response.reset(); // 先去掉檔名稱中的空格,然後轉換編碼格式為utf-8,保證不出現亂碼,這個檔名稱用於瀏覽器的下載框中自動顯示的檔名 response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"), "iso8859-1")); response.addHeader("Content-Length", "" + contentLength); OutputStream os = new BufferedOutputStream(response.getOutputStream()); //response.setContentType("application/octet-stream"); response.setContentType("application/vnd.ms-excel"); os.write(buffer);// 輸出檔案 os.flush(); os.close(); } catch (Exception e) { e.getMessage(); } } @GetMapping("downProcessFile2.do") @ApiOperation(value = "test匯出2", tags = {"productAccess"}, httpMethod = "GET") public void downProcessFile2() throws Exception{ String getURL="
http://fsmartbucket-30011.sz.gfp.tencent-cloud.com/123aa21088d846d8931cb463defd6694xlsx
"; URL getUrl = new URL(getURL); // 根據拼湊的URL,開啟連線,URL.openConnection函式會根據URL的型別, // 返回不同的URLConnection子類的物件,這裡URL是一個http,因此實際返回的是HttpURLConnection HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection(); // 進行連線,但是實際上get request要在下一句的connection.getInputStream()函式中才會真正發到 // 伺服器 connection.setConnectTimeout(25000); connection.setReadTimeout(25000); connection.connect(); int status = connection.getResponseCode(); if (status == 200) { DataInputStream in = new DataInputStream( connection.getInputStream()); DataOutputStream out = new DataOutputStream(new FileOutputStream("abc.xlsx")); byte[] buffer = new byte[4096]; int count = 0; while ((count = in.read(buffer)) > 0) { out.write(buffer, 0, count); } out.close(); in.close(); } else { String strResponse = "error"; } connection.disconnect(); } /** * 產品手冊批量下載(以壓縮包的格式) * * @param request * @param response * @return * @throws Exception */ @RequestMapping("downloadManual") public HttpServletResponse downLoadFiles(HttpServletRequest request, HttpServletResponse response) throws Exception { try { File dir = new File("E:\\manual\\"); *//**建立一個臨時壓縮檔案,我們會把檔案流全部注入到這個檔案中,這裡的檔案你可以自定義是.rar還是.zip**//* File file = new File("E:/manual.rar"); if (!file.exists()) { file.createNewFile(); } response.reset(); return downloadZip(file, response); } catch (Exception e) { e.printStackTrace(); } *//**直到檔案的打包已經成功了,檔案的打包過程被我封裝在FileUtil.zipFile這個靜態方法中,稍後會呈現出來,接下來的就是往客戶端寫資料了**//* return response; } /** * 以流的形式下載檔案 * * @param file * @param response * @return */ public static HttpServletResponse downloadZip(File file, HttpServletResponse response) { try { // 以流的形式下載檔案。 InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath())); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); //如果輸出的是中文名的檔案,在此處就要用URLEncoder.encode方法進行處理 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8")); toClient.write(buffer); toClient.flush(); toClient.close(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { File f = new File(file.getPath()); // f.delete(); } catch (Exception e) { e.printStackTrace(); } } return response; } /** * 根據輸入的檔案與輸出流對檔案進行打包 * * @param inputFile * @param ouputStream */ public static void zipFile(File inputFile, ZipOutputStream ouputStream) { try { if (inputFile.exists()) { *//**如果是目錄的話這裡是不採取操作的,至於目錄的打包正在研究中**//* if (inputFile.isFile()) { FileInputStream IN = new FileInputStream(inputFile); BufferedInputStream bins = new BufferedInputStream(IN, 1024); //org.apache.tools.zip.ZipEntry ZipEntry entry = new ZipEntry(inputFile.getName()); ouputStream.putNextEntry(entry); // 向壓縮檔案中輸出資料 int nNumber; byte[] buffer = new byte[1024]; while ((nNumber = bins.read(buffer)) != -1) { ouputStream.write(buffer, 0, nNumber); } // 關閉建立的流物件 bins.close(); IN.close(); } else { try { File[] files = inputFile.listFiles(); for (int i = 0; i < files.length; i++) { zipFile(files[i], ouputStream); } } catch (Exception e) { e.printStackTrace(); } } } } catch (Exception e) { e.printStackTrace(); } } @GetMapping("downProcessFile3.do") @ApiOperation(value = "test匯出3", tags = {"productAccess"}, httpMethod = "GET") public Response<JSONObject> downProcessFile3(String url, String name, HttpServletResponse response) { String url2="
http://fsmartbucket-30011.sz.gfp.tencent-cloud.com/123aa21088d846d8931cb463defd6694xlsx
"; HttpURLConnection conn = null; try { URL path = new URL(url2); conn = (HttpURLConnection) path.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); InputStream fis = conn.getInputStream();// 通過輸入流獲取資料 byte[] buffer = readInputStream(fis); if (null != buffer && buffer.length > 0) { // 清空response response.reset(); // 設定response的Header response.addHeader("Content-Disposition","attachment;filename="+ new String(("abc.xlsx").getBytes("GBK"),"ISO8859_1")); response.addHeader("Content-Length", "" + buffer.length); OutputStream toClient = response.getOutputStream(); response.setContentType("application/octet-stream"); toClient.write(buffer); toClient.flush(); toClient.close(); } } catch (IOException ex) { ex.printStackTrace(); }finally { if(conn != null) { conn.disconnect(); } } } /** * 從輸入流中獲取資料 * @param fis 輸入流 * @return * @throws IOException */ private byte[] readInputStream(InputStream fis) throws IOException { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while( (len=fis.read(buffer)) != -1 ){ outStream.write(buffer, 0, len); } fis.close(); return outStream.toByteArray(); }