1. 程式人生 > >前臺通過base64傳圖片到後臺的實現方法

前臺通過base64傳圖片到後臺的實現方法

前臺將圖片轉換為base64的方法如下:

$("#article_image").change(function(){
    var file = this.files[0];
        //判斷型別是不是圖片  
        if(!/image\/\w+/.test(file.type)){     
                alert("請確保檔案為影象型別");   
                return false;   
        }   
        var reader = new FileReader();   
        reader.readAsDataURL(file);   
        reader.onload = function(e){
          image_base64=this.result.split(",")[1];
           //就是base64 
          article_image = image_base64;   
        }
  });

後臺程式碼接受base64的值,轉換為圖片後儲存返回儲存的url
 @RequestMapping(value = "/uploadPoster.do")  
    public @ResponseBody Object uploadPoster(HttpServletRequest request,  
                HttpServletResponse response) throws Exception {  
            HttpJson httpJson = new HttpJson();  
            System.out.println("開始上傳照片");  
             String customerId = request.getParameter("computecustomerId");  
            String ret_fileName = null;// 返回給前端已修改的圖片名稱  
            String base64Img = request.getParameter("base64");  
            // 臨時檔案路徑  
            //String dirTemp = "\\upload\\temp";  
            String dirTemp = "\\upload";  
            String uploadImg = "\\upload";  
  
            try {  
                request.setCharacterEncoding("UTF-8");  
            } catch (UnsupportedEncodingException e1) {  
                // TODO Auto-generated catch block  
                e1.printStackTrace();  
                httpJson.setMsg("上傳圖片失敗");  
                httpJson.setSuccess(false);  
                return httpJson;  
            }  
            // response.setContentType("text/html; charset=UTF-8");  
            // PrintWriter out = response.getWriter();  
  
            String realPath = request.getServletContext().getRealPath("");  
            String tempPath = request.getServletContext().getRealPath("/")  
                    + dirTemp;  
            File file_normer = new File(realPath + uploadImg+"/"+customerId);  
            if (!file_normer.exists()) {  
                file_normer.mkdirs();  
            }  
            // 用於設定圖片過大,存入臨時檔案  
            DiskFileItemFactory factory = new DiskFileItemFactory();  
            factory.setSizeThreshold(20 * 1024 * 1024); // 設定使用記憶體超過5M時,將產生臨時檔案並存儲於臨時目錄中。  
            factory.setRepository(new File(tempPath)); // 設定儲存臨時檔案的目錄。  
  
            ServletFileUpload upload = new ServletFileUpload(factory);  
            upload.setHeaderEncoding("UTF-8");  
             if (base64Img == null) // 影象資料為空    
                    return false;    
             base64Img = base64Img.replaceAll("data:image/jpeg;base64,", "");    
                BASE64Decoder decoder = new BASE64Decoder();    
                try {    
                    // Base64解碼    
                    byte[] b = decoder.decodeBuffer(base64Img);    
                    for (int i = 0; i < b.length; ++i) {    
                        if (b[i] < 0) {// 調整異常資料    
                            b[i] += 256;    
                        }    
                    }    
                    // 生成jpeg圖片    
                    ret_fileName = new String((DateHandler.dateToStr(new Date(),"yyyyMMddhhmmss")+".jpg").getBytes("gb2312"), "ISO8859-1" ) ;   
                    File file = new File(realPath + uploadImg+"/"+ customerId + "/" + ret_fileName);  
                    OutputStream out = new FileOutputStream(file);    
                    out.write(b);    
                    out.flush();    
                    out.close();    
                } catch (Exception e) {    
                    e.printStackTrace();    
                }    
              
                String image_url = request.getSession().getServletContext() .getContextPath()+ "/upload/" + customerId + "/" + ret_fileName;  
            // 將已修改的圖片url對應的id返回前端  
            httpJson.setMsg("上傳圖片成功");  
            httpJson.setSuccess(true);  
            httpJson.setObj(image_url);  
            return JSONObject.fromObject(httpJson);  
           }  
      
        }  

17級徐朝暉 2017年3月16日