티스토리 뷰

728x90
반응형

 

 

영상을 base64로 encode 하고 바로 src에 때려 넣으면 5초밖에 재생이안됨.

 

1. 저장하기

javascript

//file을 Blob으로 변환
function getfileToBlob(){
	var reader = new FileReader();
	reader.readAsDataURL(file);
	reader.onload = function(event){
		var dataURL = event.target.result;
		var base64 = dataURL.substr(dataURL.indexOf('base64,')+7);
		var file_etc = dataURL.substring(dataURL.indexOf(':')+1,dataURL.indexOf(';'));
        				
		var blob = b64toBlob(base64,file_etc);
		var blobUrl = URL.createObjectURL(blob);// blobUrl을 src에 넣으면 5초이상 재생가능
	}
}

//base64를 Blob으로 변환
function b64toBlob(b64Data,contentType){
    	var sliceSize=512;
    	  const byteCharacters = atob(b64Data);
    	  const byteArrays = [];

    	  for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    	    const slice = byteCharacters.slice(offset, offset + sliceSize);

    	    const byteNumbers = new Array(slice.length);
    	    for (var i = 0; i < slice.length; i++) {
    	      byteNumbers[i] = slice.charCodeAt(i);
    	    }

    	    const byteArray = new Uint8Array(byteNumbers);
    	    byteArrays.push(byteArray);
    	  }

    	  const blob = new Blob(byteArrays, {type: contentType});
    	  return blob;
    	}
function send(){
	var URL = 'save.do';//전송할 url
    var formData - new FormData(); //blob을 서버로 전송할때 formData를 사용, file처럼 인식하는듯?
    formData.append('blob',blob, fileName); // (key,value,파일명)
    formData.append('file_etc',file_etc);
	
    $.ajax({
		method : "POST",
		url : URL,
		processData: false, 
  		contentType: false, 
		data : formdata,
		beforeSend: function() {
		}, success : function (data) {
		
        }

}

controller

@RequestMapping(value = "/save.do", method = RequestMethod.POST, produces = "application/text; charset=UTF-8")
@ResponseBody
public String save(@RequestParam Map<String, Object> paramMap,MultipartHttpServletRequest multipartRequest) throws Exception {
	    
	MultipartFile file = multipartRequest.getFile("blob");
    
    if(!file.isEmpty()){			
			paramMap.put("VIDEO", convertFileToByte(file));
		}
    
	Service.saveVideo(paramMap);
    
	return "";
}

//파일을 byte[] 로 변환
private byte[] convertFileToByte(MultipartFile mfile) throws Exception {
		File file = new File(mfile.getOriginalFilename());
		file.createNewFile();
		FileOutputStream fos = new FileOutputStream(file);
		fos.write(mfile.getBytes());
		
		byte[] returnValue = null;		
		ByteArrayOutputStream baos = null;	    
	    FileInputStream fis = null;
	  
	    try {
	    	
	    	baos = new ByteArrayOutputStream();
	    	fis = new FileInputStream(file);
	    		    	
	        byte[] buf = new byte[1024];
	        int read = 0;
	        
	        while ((read=fis.read(buf,0,buf.length)) != -1){
	        	baos.write(buf,0,read);
	        }
	        
	        returnValue = baos.toByteArray();
	   
	    } catch (Exception e) {
	        throw e;
	    } finally {
	            if (baos != null) {
	            	baos.close();
	            }
	            if (fis != null) {
	            	fis.close();
	            }
	    }
	    
	    fos.close();
	    return returnValue;
	}

 

sql.xml

<insert id="save" parameterType="java.util.Map">
    INSERT INTO VIDEO (
        VIDEO_ETC,
        VIDEO	        
    ) VALUES (
        #{file_etc},
        #{VIDEO, jdbcType=BLOB, javaType=[B}	        
    )
</insert>

2.불러오기

sql.xml

<resultMap type="java.util.Map" id="videoMap">
	<result property="VIDEO_ETC" column="VIDEO_ETC"/>
	<result property="base64" column="VIDEO" javaType="[B" jdbcType="BLOB"/>
</resultMap>
<select id="selectVideo" resultMap="videoMap">
	SELECT VIDEO_ETC,VIDEO FROM TB_VIDEO
</select>

controller

@RequestMapping(value="Video.do")
public String Video(HttpServletRequest request,HttpServletResponse response) throws Exception {
	
    Map<String,Object> resultMap = Service.selectVideo(); 
	try {	
        byte[] arr = (byte[]) resultMap.get("base64");
        response.setContentType(resultMap.get("VIDEO_ETC").toString());
        response.getOutputStream().write(video);
        response.getOutputStream().close();
	
    } catch (Exception e) {
			e.printStackTrace();
		}
}

jsp

<video controls autoplay>
	<source src="Video.do">
</video>

 

 

3. 업로드한 video 바로 재생 시키는법.

위에 코드를 응용

 

function(){
    var file = $('input[type=file]')[0].files[0]

    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(event){
        var dataURL = event.target.result;
        var base64 = dataURL.substr(dataURL.indexOf('base64,')+7);
        file_etc = dataURL.substring(dataURL.indexOf(':')+1,dataURL.indexOf(';'));

        blob = b64toBlob(base64,file_etc);
        var blobUrl = URL.createObjectURL(blob);
        var $video = $('#video');

        $video.html('<source src="'+blobUrl+'" type="'+blob_etc+'">');
        video[0].load();
    }
}

 

 

728x90
반응형
댓글

"이 블로그의 모든 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday