1. 程式人生 > >java上傳照片附件

java上傳照片附件

!= object con pat false fun nal 生成 ole

是個小的知識點,但因為一個小細節浪費了大半天的時間才弄好,

@ResponseBody
    @RequestMapping("/upLoadJdjdImage")
    public ModelMap upLoadJdjdImage(HttpServletResponse response, ModelMap model,@RequestBody String jsonString){
        String code= "", msg= "";
        boolean success= false;
        try {
            String json
= URLDecoder.decode(jsonString, "utf-8"); JSONObject jsonObj= new JSONObject(json); String photo= jsonObj.getString("photo");

我這邊是用java service接收到android端的照片,照片格式為用base64處理的二進制圖片,按照一般的思路就是直接接收後,生成一個圖片文件,

然後用流寫進數據,

/**上傳照片*/
	public String upload(String photo, HttpServletResponse response, String savePath) {
		response.setContentType("text/html");
		BufferedOutputStream bos = null;
		File newFile = null;
		String fileName="";
		try {
			File file= new File(savePath);
			if(!file.exists()){//判斷路徑下是否有此文件
				file.mkdir();//創建此抽象路徑名指定的目錄。
			}
			if(photo.length()>0){
				byte [] by= null;
				BASE64Decoder base64= new BASE64Decoder();
				by= base64.decodeBuffer(photo);
				String newPath= savePath +"\\" + System.currentTimeMillis() + ".jpg"; 
				newFile= new File(newPath);
				bos= new BufferedOutputStream(new FileOutputStream(newFile));
				bos.write(by);
				bos.flush();
				fileName=newFile.getName();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return fileName;
	}

  然而,看了下路徑下面寫出的圖片,居然是純黑的,這個服務中也沒有異常拋出,在網上查了其他的圖片寫法,基本上都是一致這樣寫的

圖片,然後就很懵逼了,後面問了前輩才了解到,這樣接收的二進制數據還需要對字符進行處理

              String json= URLDecoder.decode(jsonString, "utf-8");
			JSONObject jsonObj= new JSONObject(json);
			String photo= jsonObj.getString("photo");
			photo= photo.replace("data:image/png;base64", "");
			photo= photo.replaceAll("data:image/jpeg;base64", "");
			photo= photo.replace(" ", "+");//替換空字符串為+
			photo= photo.replace("\n", ""); //置空換行符
			photo= photo.replace("\t", "");
			photo= photo.replace("\r", "");
			//photo= photo.replace("/", ""); //過慮轉義符

  需要替換部分特殊字符,這應該算是一個比較冷的小知識點了,這邊記錄一下,希望可以幫助後面的同學,最後附屬php二進制圖片數據

的處理

 function Img($str,$imgName=null)//base64 生成圖片保存
    {   
        if( $imgName ){
            unlink(ROOT_PATH.‘/public/uploads/‘.$imgName);  //刪除原圖
        }
        $saveName = request()->time() .rand_string(4). ‘.jpg‘; //圖片名生成  
        $str = str_replace(‘ ‘, ‘+‘, $str); //替換空字符串為+
        $str = str_replace(‘\n‘, ‘‘,$str);  //置空換行符
        $str = str_replace(‘\t‘, ‘‘,$str); 
        $str = str_replace(‘\r‘, ‘‘,$str);
        $str = stripslashes($str);  //過慮轉義符      
        $str = str_replace(‘data:image/jpeg;base64,‘, ‘‘, $str);
        $str = str_replace(‘data:image/png;base64,‘, ‘‘, $str);
        $img = base64_decode($str); //解碼  
        file_put_contents(ROOT_PATH . ‘/public/uploads/‘ . $saveName,$img); //保存圖片
        $img_url = ‘/uploads/‘.$saveName;  //生成圖片保存路徑
        return $img_url;
    }

  

java上傳照片附件