標籤:toc 調整 tty utf-8 path 通過 ref odi imp
原文地址:http://blog.csdn.net/tonyfreak/article/details/72522855思路
前台傳以data:image/jpeg;base64,開頭的base64編碼的String字串,後台接收字串以後先進行base64解碼 .decodeBuffer(),轉換成二進位編碼,然後使用位元組輸出資料流FileOutputStream()將檔案儲存到指定目錄下。
報下面的錯誤
Error parsing HTTP request header
Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
要修改tomcat下sever.xml,header的大小
<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8000" protocol="HTTP/1.1" redirectPort="8443" maxHttpHeaderSize="10485760"/>
將base64編碼轉成二進位
// 通過base64來轉化圖片 imageFile = imageFile.replaceAll("data:image/jpeg;base64,", ""); BASE64Decoder decoder = new BASE64Decoder(); // Base64解碼 byte[] imageByte = null; try { imageByte = decoder.decodeBuffer(imageFile); for (int i = 0; i < imageByte.length; ++i) { if (imageByte[i] < 0) {// 調整異常資料 imageByte[i] += 256; } } } catch (Exception e) { e.printStackTrace(); }
將二進位轉成file檔案
// 組建檔案名 String files = new SimpleDateFormat("yyyyMMddHHmmssSSS") .format(new Date()) + (new Random().nextInt(9000) % (9000 - 1000 + 1) + 1000) + ".png"; // 組建檔案路徑 String filename = Constant.UPLOAD_PATH + files; try { // 組建檔案 File imageFile = new File(filename); imageFile.createNewFile(); if(!imageFile.exists()){ imageFile.createNewFile(); } OutputStream imageStream = new FileOutputStream(imageFile); imageStream.write(imageByte); imageStream.flush(); imageStream.close(); } catch (Exception e) { e.printStackTrace(); }
BASE64Encoder的到期警告,因為是sun的內部API,而不推薦使用,因為後期可能被刪除的潛在風險,所以用commons-codec來代替再合適不過了
logo = logo.replaceAll("data:image/png;base64,", ""); Base64 decoder = new Base64(); // Base64解碼 byte[] imageByte = null; try { imageByte = decoder.decode(logo);
base64編碼上傳圖片java後台接收執行個體