1. 程式人生 > 其它 >檔案下載轉碼處理類

檔案下載轉碼處理類

import org.apache.commons.codec.binary.Base64;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;


//1.檔案下載(postman可試)
public static void postmanLoad(String url, HttpServletResponse response) throws Exception {

        File file = new
File(url); byte [] bytes = File2byte(file); try { response.setHeader("Content-Disposition", "attachment; filename=\"" + "123.jpg" + "\""); OutputStream out = response.getOutputStream(); if (bytes != null) { out.write(bytes); } out.close(); }
catch (Exception e) { e.printStackTrace(); } }
/** * 將檔案轉換成byte陣列 */ public static byte[] File2byte(File tradeFile){ byte[] buffer = null; try { FileInputStream fis = new FileInputStream(tradeFile); ByteArrayOutputStream bos
= new ByteArrayOutputStream(); byte[] b = new byte[10240]; int n; while ((n = fis.read(b)) != -1) { bos.write(b, 0, n); } fis.close(); bos.close(); buffer = bos.toByteArray(); }catch (FileNotFoundException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } return buffer; }
//2.從地址下載轉成Base64編碼 public static String downLoadFromUrlBase64(String urlStr) throws Exception { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //設定超時間為10秒 conn.setConnectTimeout(10 * 1000); //得到輸入流 InputStream inputStream = conn.getInputStream(); return DownLoadFileUtil.getBase64FromInputStream(inputStream); } /** * 將inputstream轉為Base64 public static String getBase64FromInputStream(InputStream is) throws Exception { // 將圖片檔案轉化為位元組陣列字串,並對其進行Base64編碼處理 byte[] data = null; // 讀取圖片位元組陣列 try { ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); byte[] buff = new byte[100]; int rc = 0; while ((rc = is.read(buff, 0, 100)) > 0) { swapStream.write(buff, 0, rc); } data = swapStream.toByteArray(); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { throw new Exception("輸入流關閉異常"); } } } return Base64.encodeBase64String(data); }