JAVA 文件與base64之間的轉化, 以及Web實現base64上傳文件

<1>文件與base64字符串之間的轉化html

package servlet_file_upload; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; /** * base64 與 file 之間的相互轉化 * 實現形式, 懶漢式的單例模式 */ public class Base64UploadClass { // 私有化構造器 private Base64UploadClass() { } // 事先定義一個變量存放該類的實例 private static Base64UploadClass fileBase64 = null; // 對外暴露一個靜態方法獲取該類的實例 public static Base64UploadClass getFileBase64() { if (fileBase64 == null) { fileBase64 = new Base64UploadClass(); } return fileBase64; } // 將 file 轉化爲 Base64 public String fileToBase64(String path) { File file = new File(path); FileInputStream inputFile; try { inputFile = new FileInputStream(file); byte[] buffer = new byte[(int) file.length()]; inputFile.read(buffer); inputFile.close(); return new BASE64Encoder().encode(buffer); } catch (Exception e) { throw new RuntimeException("文件路徑無效\n" + e.getMessage()); } } // 將 base64 轉化爲 file public boolean base64ToFile(String base64, String path) { byte[] buffer; try { buffer = new BASE64Decoder().decodeBuffer(base64); FileOutputStream out = new FileOutputStream(path); out.write(buffer); out.close(); return true; } catch (Exception e) { throw new RuntimeException("base64字符串異常或地址異常\n" + e.getMessage()); } } }

<2> servlet 藉助 base64 實現文件上傳前端

package servlet_file_upload; import java.io.IOException; import java.net.URLDecoder; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/Base64UploadServlet") public class Base64UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public Base64UploadServlet() { super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 容許跨域訪問,並設置請求編碼和輸出編碼爲 UTF-8 response.addHeader("Access-Control-Allow-Origin", "*"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); // 獲取文件將要保存到的文件夾路徑 String path = getServletContext().getRealPath(""); // 接收base64文件字符串, 並對文件字符串進行解碼 String fileContent = request.getParameter("file"); fileContent = URLDecoder.decode(fileContent, "UTF-8"); // 獲取文件保存的相對路徑 String returnPath = "Upload/" + System.currentTimeMillis() + "." + fileContent.split("\\.")[1]; // 保存文件返回路徑 Base64UploadClass fileBase64 = Base64UploadClass.getFileBase64(); if(fileBase64.base64ToFile(fileContent.split("\\.")[0], path + returnPath)){ response.getWriter().write(returnPath); } else { response.getWriter().write("上傳失敗"); } } }

 

前端代碼參考:  http://www.cnblogs.com/lovling/p/6686688.htmljava

相關文章
相關標籤/搜索