<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