JAVA 上傳圖片保存到sql server 二進制字段類型(存取)

人狠話不多,直接上代碼---

JSP如下:

 <form id="form"  method="post"	enctype="multipart/form-data">
	<div class="container kv-main" style="width:100%;height: 300px">   
           <input id="file"   name="file" type="file"  >
    </div> 
</form>

JS如下:

var formData = new FormData($("#form")[0]);   
	$.ajax({
		url : '您的url',
		type : 'post',
		data : formData,
		async: false,
		contentType: false,
		processData: false,
		success : function(resule) {
	        layer.msg('保存成功!');
		},
		error : function(resule) {
			layer.msg('保存失敗!');
		}
});

controller如下:

@RequestMapping("/SaveEntry") 
@ResponseBody
public String SaveEntry(TblUser tblUser,@RequestParam(value="file",required=true) MultipartFile  file,HttpServletRequest request) throws Exception{ 
		 	 
	if(!file.isEmpty()){
		          
		tblUser.setImgSignature(file.getBytes());
	}
				  
		int i =  tbUserService.SaveEntry(tblUser); 
		if(i == 1)
		{
			result.put("statusCode", 100); 
		}else 
		{
			result.put("statusCode", 300);
		}  
			 
			return result.toString(); 
		
} 

po字段類型用byte[] 

private byte[] imgSignature;

public byte[] getImgSignature() {
		return imgSignature;
	}

	public void setImgSignature(byte[] imgSignature) {
		this.imgSignature = imgSignature;
	}
	

server/dao 上面 作保存操作。代碼就不貼出來了

mapping 上面重要的一點就是類型要對應,不然會報錯,報xxx字段類型和sql server 中的字段類型不兼容的問題。我這裏java 用byte[]  在mybatis上面的 mapping 就對應如下

   <result column="imgSignature" property="imgSignature" jdbcType="LONGVARBINARY" />
 

 

sql server 對應字段如下:

 

以上就是保存圖片的操作了。

獲取二進制數據流的操作比較簡單:

control上面如下:

@RequestMapping("/getImage") 
		  public void getImage(Integer id, HttpServletResponse response){
		        try {
		        	TblUser TbUser= tbUserService.FindById(id);
		  		  
		            byte[] image = (byte[])TbUser.getImgSignature();
		            String value = new String(image,"UTF-8");
		               for(int i=0;i<image.length;i++){
		                if(image[i]<0){
		                	image[i]+=256;
		                }
		            }
		            response.setContentType("image/jpeg");
		            ServletOutputStream out = response.getOutputStream();
		            out.write(image);
		            out.flush();
		            out.close();
		        }catch (Exception e){
		            e.printStackTrace();
		        }

		      
		    } 

jsp 直接調用即可:

<img src="xxx/getImage.do?id=1" class="kv-preview-data file-preview-image"  style="width:auto;height:160px;">

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章