自定義圖片視頻上傳插件

由於項目需要,自定義開發了一個圖片視頻上傳的插件

圖片視頻添加、移除、上傳、進度條。

主要採用websocket實現圖片分片上傳和進度條。

返回結果爲圖片服務器中保存的圖片的實際名稱。

效果圖:

關鍵代碼:

index.html

$("#btn").click(function(){
	var photovideo = photoVideo();
	photovideo.openUploadWindow();
})

photoVideo.js 


var photoVideo = (function(windows){
	
	var photoVideo = function(){
		return new photoVideo.fn.init();
	}
	
	photoVideo.fn = photoVideo.prototype = {
		
		constructor:photoVideo,
		init: function(){
			this.serverUrl = "http://gdt.xxz.gov.cn:8015"; //接收圖片服務地址
			this.fileSplitSize = 50000; //資源分片大小
			this.stompClient = {};	//stom客戶
			this.uploadStatus = false;//上傳狀態
			this.uploadList = [];//上傳列表
			this.resultList = [];//上傳成功結果列表
			this.uuid = this.getUuid();//生成唯一標識
			this.webSocketConnect();//建立webSocket鏈接並獲取鏈接唯一標識
			this.key = "";//傳輸通道標識
		},
		openUploadWindow: function(){	//設置圖片和視頻上傳的窗口顯示
			var me = this;
			$("body").append('<div class="upload_background">'+
								'<div class="upload_window">'+
									'<div class="upload_title">'+
										'圖片視頻上傳'+
									'</div>'+
									'<div class="upload_content">'+
										'<div class="photo_area">'+
											'<div class="pv_title">圖片</div>'+
											'<div id="photo_content" class="pv_content">'+
												'<div class="pv_add">'+
													'<input class="pv_input" type="file" name="" id="uploadImg" multiple accept="image/*">'+
												'</div>'+
											'</div>'+
											
										'</div>'+
										'<div class="video_area">'+
											'<div class="pv_title">視頻</div>'+
											'<div id="video_content" class="pv_content">'+
												'<div class="pv_add">'+
													'<input class="pv_input" type="file" name="" id="uploadVideo" multiple accept="video/*">'+
												'</div>'+
											'</div>'+
										'</div>'+
									'</div>'+
									'<div class="upload_btn">上傳圖片&視頻</div>'+
								'</div>'+
							'</div>');
			//點擊標題欄關閉
			$(".upload_title").click(function(){
				if(me.uploadStatus){
					alert("正在上傳請勿操作");
					return;
				}
				me.closeUploadWindow();
			});
			//圖片上傳點擊事件
			$("#uploadImg").change(function(){
				me.readFile(this,"img");
			});
			//視頻上傳點擊事件
			$("#uploadVideo").change(function(){
				me.readFile(this,"video");
			});
			//上傳
			$(".upload_btn").on("click",function(){
				if(me.uploadStatus){
					alert("正在上傳請勿重複提交");
					return;
				}
				me.upload();
			});
			
		},
		closeUploadWindow: function(){	//關閉上傳接口
			var me = this;
			var res = true;
			if(me.resultList.length != 0){
				res = confirm("退出將不保留已經上傳的記錄!");
			}
			if(res){
				me.init();  //關閉前重新初始化
				$(".upload_background").remove();//關閉窗口
			}
		
			
		},
		readFile: function(obj,type){//處理圖片並添加都dom中的函數
			var me = this;
			// 獲取input裏面的文件組
			var fileList = obj.files;
			if(($("#photo_content>div").each(function(){}).length + fileList.length > 4&&type=="img")||($("#video_content>div").each(function(){}).length + fileList.length > 4&&type=="video")){
				alert("最多選擇三張"+type);
				return;
			}
			//對文件組進行遍歷,可以到控制檯打印出fileList去看看
			for(var i=0;i<fileList.length;i++){
				var reader= new FileReader();
				reader.readAsDataURL(fileList[i]);
				(function(_i){ 
					// 當文件讀取成功時執行的函數
					reader.onload=function(e){
						//將結果添加到待上傳列表中
						var url = "'"+URL.createObjectURL(fileList[_i])+"'";
						me.uploadList.push({
							name: fileList[_i].name,
							size: fileList[_i].size,
							data: this.result,
							type: type,
							url: url
						});
						if(type == "img"){
							$("#photo_content").prepend('<div class="pv_photo"><span data-name="'+fileList[_i].name+'"></span><img src="'+this.result+'"/><div class="loading"><div></div></div></div>');
							if($("#photo_content>div").each(function(){}).length >= 4){
								$("#photo_content .pv_add").hide();
							}
						}else{
							/* <video id="video" poster="封面圖路徑" src="'+url+'" controls="controls" x5-playsinline="" playsinline="" webkit-playsinline preload="auto"></video> */
							$("#video_content").prepend('<div class="pv_photo"><span data-name="'+fileList[_i].name+'"></span><div class="loading" style="margin-top:70px"><div></div></div></div>');
							if($("#video_content>div").each(function(){}).length >= 4){
								$("#video_content .pv_add").hide();
							}
						}
						$(".pv_photo span").off("click").on("click",function(){
							me.remove(this);
						})
					}
				})(i);
			}
		
		},
		remove: function(e){//移除已經選擇的圖片或視頻
			var me = this;
			if(me.uploadStatus){
				alert("正在上傳請勿操作");
				return;
			}
			$(e).parent().remove();//移除dom節點
			for(var j=0; j<me.uploadList.length;j++){//移除上傳列表中的對應值
				if(me.uploadList[j].name == $(e).attr("data-name"))
					me.uploadList.splice(j,1);
			}
			//判斷增加按鈕是否顯示
			if($("#video_content>div").each(function(){}).length < 4){
				$("#video_content .pv_add").show();
			}
			if($("#photo_content>div").each(function(){}).length < 4){
				$("#photo_content .pv_add").show();
			}
		},
		playVideo: function(url){//圖片視頻預覽
			console.log(url);
		},
		upload:function(){//上傳列表中的視頻和圖片
			var me = this;
			if(me.uploadList.length == 0){//禁止上傳空數據
				alert("未選擇圖片或視頻");
				return;
			}
			
			//上傳過程中 設置用戶禁止操作
			me.setLock();
		
			//顯示上傳進度
			$(".loading").show();
			
			//本次要上傳的數據源屬性
			var uploadSource = {
				photo:0,
				video:0,
				size:0,
			}
			for(var i=0; i<me.uploadList.length;i++){
				if(me.uploadList[i].type == "img"){
					uploadSource.photo++;
				}else{
					uploadSource.video++;
				}
				uploadSource.size += me.uploadList[i].size;
			}
			//向服務器發送要傳輸的內容屬性 並請求建立傳輸通道
			me.stompClient.send("/sockjs/sourcefromclient",{auth:me.uuid},JSON.stringify(uploadSource));
			
			
		},
		webSocketConnect:function(){//建立webSocket連接
			var me = this;
			var socket = new SockJS(me.serverUrl + '/sockjs/endpoint');
			me.stompClient = Stomp.over(socket);
			me.stompClient.debug = null;
			//建立stom連接
			me.stompClient.connect({auth:me.uuid}, function(frame) {
				//接受服務器源數據響應
				me.stompClient.subscribe('/user/topic/source', function(data) {
					var rsz = JSON.parse(data.body);
					//服務器響應通道建立請求後的操作
					if(rsz.status != "success"){
						alert("服務器響應失敗");
						return;
					}
					
					//設置通道key
					me.key = rsz.key;
				 
					//組裝分片信息
					var fp = {
						id:0,//第幾片
						total:0,//共幾片
						filesplitsize:me.fileSplitSize,
						name:"",//名稱
						date: Date.parse(new Date()),//本次傳輸發生的時間
						data:"",//分片數據
					};
					for(var i=0; i<me.uploadList.length;i++){
						var s = me.uploadList[i];
						var d_source = s.data.split(",")[1];
						var l = Math.ceil(d_source.length/me.fileSplitSize);
						fp.name = s.name;
						fp.total = l;
						//初始化返回結果
						me.resultList.push({
							name: me.key+fp.date+fp.name,//圖片保存名稱
							total:fp.total,//分片總數
							success:0,//成功條數
							fail:0,//失敗條數
							status:false,//上傳狀態
							failData:[]//失敗內容列表
						})
						for(var j=0; j<l; j++){
							fp.id = j+1;//設定當前片數
							fp.data = d_source.substring(j*me.fileSplitSize,(j*me.fileSplitSize+me.fileSplitSize));//設置每片內容
							me.sendImgOrVideo(JSON.stringify(fp));//發送數據到服務器
						}
					} 
				});
				//接受服務器對每個數據片的響應結果
				me.stompClient.subscribe('/user/topic/message', function(data) {
					
					var rs = JSON.parse(data.body);//獲取響應結果
					var statusNum = 0;//已經傳輸完成的個數
					for(var i=0;i<me.resultList.length;i++){
						if(me.resultList[i].name == rs.name){
							if(rs.status == "success"){
								//記錄成功數量
								me.resultList[i].success++;
							}else{
								//記錄失敗數量
								me.resultList[i].fail++;
								//記錄失敗內容等待重傳
								me.resultList[i].failData.push(rs.failData); 
							}
							
							//設置進度條
							$(".pv_photo").children(".loading").eq(i).children("div").css("width",(me.resultList[i].success)/rs.total*100+"%");
							//設置成功樣式
							if(me.resultList[i].success == rs.total){
								$(".pv_photo").children(".loading").eq(i).children("div").css("background","#54e34a");
							}
							//設置失敗樣式
							if(me.resultList[i].fail != 0){
								$(".pv_photo").children(".loading").eq(i).children("div").css("background","#cc1a1a");
							}
						}
						//判斷單個是否完成
						if((me.resultList[i].success + me.resultList[i].fail) == me.resultList[i].total)
							me.resultList[i].status = true;
						//判斷全部是否完成
						if(me.resultList[i].status)
							statusNum++;
					}
					//全部傳輸完畢
					if(statusNum == me.resultList.length){
						$(".upload_btn").off("click");//清除點擊事件
						me.clearLock();//解鎖禁用了的按鈕
						var reloadStatus = false;//是否進行重傳
						//判定是否存在失敗的
						for(var h = 0;h<statusNum;h++){
							if(me.resultList[h].failData.length != 0){
								reloadStatus = true;
							}
						}
						if(reloadStatus){
							//設置失敗後按鈕的樣式和事件
							$(".upload_btn").css("background","#e94513");
							$(".upload_btn").text("上傳失敗,點擊重試");
							
							$(".upload_btn").on("click",function(){
								for(var t = 0;t<statusNum;t++){
									if(me.resultList[t].failData.length != 0){
										for(var m = 0;m<me.resultList[t].failData.length;m++ )
											me.sendImgOrVideo(me.resultList[t].failData[m]);//重新發送
									}
								}
							})
						}else{
							//設置成功後按鈕的樣式和點擊事件
							$(".upload_btn").css("background","#03A9F4");
							$(".upload_btn").text("上傳成功,點擊返回");
							$(".upload_btn").on("click",function(){
								console.log("進行你後續的工作:");
								console.log(me.resultList);
								me.init();  //關閉前重新初始化
								$(".upload_background").remove();//關閉窗口
							})
						}
					}
				});
			},function errorCallBack (error) {
				alert("服務器連接失敗");
				$(".upload_background").remove();//關閉窗口
			});
		},
		sendImgOrVideo: function(data){//發送單個數據集到服務器
			var me = this;
			me.stompClient.send("/sockjs/messagefromclient",{auth:me.uuid},data);
		},
		getUuid:function(){//生成uuid
			var s = [];
			var hexDigits = "0123456789abcdef";
			for (var i = 0; i < 36; i++) {
				s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
			}
			s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
			s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
			s[8] = s[13] = s[18] = s[23] = "-";
		
			var uuid = s.join("");
			return uuid;
		},
		setLock: function(){//上傳過程中禁止用戶進行操作
			//禁用上傳和關閉按鈕
			this.uploadStatus = true;
			//設置禁用按鈕樣式
			$(".upload_btn").css("background","#d9d9d9");
			//隱藏選擇圖片和刪除圖片組件
			$(".pv_add").hide();
			$(".pv_photo>span").hide();
		},
		clearLock: function(){//清除各項按鈕鎖定
			this.uploadStatus = false;//解除鎖定標識
		}
		
	}
	
	photoVideo.fn.init.prototype = photoVideo.fn;
	return photoVideo;
})();

 photoVideo.css

.upload_background{
	width: 100%;
    background: rgba(0, 0, 0, 0.35);
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 9999;
}
.upload_window{
	width: 90%;
    height: 70%;
	margin: 25% auto 0 auto;
    background: #FFF;
    border-radius: 10px;
}
.upload_title{
	width: 100%;
    height: 10%;
    border-radius: 10px 10px 0 0;
    text-align: center;
    color: #FFF;
    font-size: 17px;
    font-family: 微軟雅黑;
    background: url(../img/close.png) no-repeat 94% center;
    background-size: 15px;
    background-color: #03A9F4;
	display:flex;
	justify-content:center;
	align-items:center;
}
.upload_content{
	width: 100%;
    height: 80%;
    border-radius: 0 0 10px 10px;
}
.upload_content>div{
	margin: 0 15px;
}
.upload_btn{
	display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 10%;
    background: #03A9F4;
    border-radius: 0 0 10px 10px;
    color: #FFF;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
}
.upload_btn:active{
	opacity: 0.7;
}
.pv_title{
	padding: 5px 0px;
    color: #524f4f;
    font-size: 14px;
    border-bottom: 1px solid #d4cfcf;
}
.pv_add{
	width: 64px;
    height: 64px;
    background: url(../img/add.png) no-repeat center center;
    background-size: 33px;
    border: 2px solid #cdcdcd;
    border-radius: 10px;
}
.pv_add:active{
	opacity: 0.7;
}
.pv_content{
	padding: 15px 0px 0 0;
	display: flex;
	justify-content: flex-start;
}
.pv_photo{
	margin-right: 10px;
    margin-bottom: 10px;
    width: 68px;
    height: 68px;
    border-radius: 10px;
	background: url(../img/video.png) no-repeat center center;
	background-size: 40px;
    background-color: #f0f0f0;
}
.pv_photo img,video{
	width: 100%;
    height: 100%;
}
.pv_photo span{
	background: url(../img/delete.png);
    background-size: 16px;
    width: 16px;
    height: 16px;
    display: block;
    position: absolute;
    margin-left: -8px;
    margin-top: -8px;
}
.pv_photo span:active{
	opacity: 0.7;
}
.pv_input{
	width: 100%;
    height: 100%;
    opacity: 0;
}
.loading{
	width: 100%;
    height: 5px;
    background: #dfdfdf;
    border-radius: 5px;
	display: none;
}
.loading div{
	height: 100%;
    width: 0%;
    background: #2196F3;
}

SockjsController.java

package com.casm.gdt.controller;


import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.casm.gdt.config.SocketSessionRegistry;
import com.casm.gdt.entriy.PhotoBurst;
import com.casm.gdt.entriy.SourceMessage;
import com.casm.gdt.service.Base64ToFile;

@Controller
public class SockjsController {
	
	@Value("${filePath}")
	private String path;
	@Autowired
    private SimpMessagingTemplate msgTemplate; 
	@Autowired
	private SocketSessionRegistry socketSessionRegistry;
	@Autowired
	private Base64ToFile base64ToFile;
	
	
	@MessageMapping("/sourcefromclient")  //接收客戶端開始發送數據請求(包含數據消息)
	public void sourcefromclient(StompHeaderAccessor stompHeaderAccessor,SourceMessage rm) {
		String agentId = stompHeaderAccessor.getNativeHeader("auth").get(0);
		String sessionId = socketSessionRegistry.getSessionIds(agentId).stream().findFirst().get();
		
		Map<String, String> rs = new HashMap<String, String>();
		rs.put("key", sessionId);
		rs.put("status", "success");
		
		msgTemplate.convertAndSendToUser(sessionId, "/topic/source", rs, createHeaders(sessionId));
		
	}
	@MessageMapping("/messagefromclient")  //接收客戶端數據消息
	public void messagefromclient(StompHeaderAccessor stompHeaderAccessor,PhotoBurst rm) {
		String agentId = stompHeaderAccessor.getNativeHeader("auth").get(0);
		String sessionId = socketSessionRegistry.getSessionIds(agentId).stream().findFirst().get();
		
		//將照片和視頻base64流存儲轉換爲文件
		boolean result = base64ToFile.base64StrToImage(rm, path+sessionId+rm.getDate()+rm.getName());
		
		Map<String, String> rs = new HashMap<String, String>();
		rs.put("name", sessionId+rm.getDate()+rm.getName());
		rs.put("id", String.valueOf(rm.getId()));
		rs.put("total", String.valueOf(rm.getTotal()));
		
		if(result) {
			rs.put("status", "success");
		}else {
			rs.put("status", "error");
			//組裝重傳數據格式
			rs.put("failData", JSON.toJSONString(rm));
		}
		msgTemplate.convertAndSendToUser(sessionId, "/topic/message", rs, createHeaders(sessionId));
	}
	
	
	
	
	private MessageHeaders createHeaders(String sessionId) {
        SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
        headerAccessor.setSessionId(sessionId);
        headerAccessor.setLeaveMutable(true);
        return headerAccessor.getMessageHeaders();
    }

	

}

SocketSessionRegistry.java

package com.casm.gdt.config;

import org.springframework.util.Assert;

import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * Created by baiguantao on 2017/8/4.
 * 用戶session記錄類
 */
public class SocketSessionRegistry{
    //this map save every session
    //這個集合存儲session
    private final ConcurrentMap<String, Set<String>> userSessionIds = new ConcurrentHashMap();
    private final Object lock = new Object();

    public SocketSessionRegistry() {
    }

    /**
     *
     * 獲取sessionId
     * @param user
     * @return
     */
    public Set<String> getSessionIds(String user) {
        Set set = (Set)this.userSessionIds.get(user);
        return set != null?set: Collections.emptySet();
    }

    /**
     * 獲取所有session
     * @return
     */
    public ConcurrentMap<String, Set<String>> getAllSessionIds() {
        return this.userSessionIds;
    }

    /**
     * register session
     * @param user
     * @param sessionId
     */
    public void registerSessionId(String user, String sessionId) {
        Assert.notNull(user, "User must not be null");
        Assert.notNull(sessionId, "Session ID must not be null");
        Object var3 = this.lock;
        synchronized(this.lock) {
            Object set = (Set)this.userSessionIds.get(user);
            if(set == null) {
                set = new CopyOnWriteArraySet();
                this.userSessionIds.put(user, (Set<String>) set);
            }

            ((Set)set).add(sessionId);
        }
    }

    public void unregisterSessionId(String userName, String sessionId) {
        Assert.notNull(userName, "User Name must not be null");
        Assert.notNull(sessionId, "Session ID must not be null");
        Object var3 = this.lock;
        synchronized(this.lock) {
            Set set = (Set)this.userSessionIds.get(userName);
            if(set != null && set.remove(sessionId) && set.isEmpty()) {
                this.userSessionIds.remove(userName);
            }

        }
    }
}

 STOMPConnectEventListener.java

package com.casm.gdt.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.web.socket.messaging.SessionConnectEvent;

/**
 * Created by baiguantao on 2017/8/4.
 * STOMP監聽類
 * 用於session註冊 以及key值獲取
 */
public class STOMPConnectEventListener  implements ApplicationListener<SessionConnectEvent> {

    @Autowired
    SocketSessionRegistry webAgentSessionRegistry;

    @Override
    public void onApplicationEvent(SessionConnectEvent event) {
        StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
        //login get from browser
        String agentId = sha.getNativeHeader("auth").get(0);
        String sessionId = sha.getSessionId();
        webAgentSessionRegistry.registerSessionId(agentId,sessionId);
    }
}

WebSocketMessageBrokerConfig.java

package com.casm.gdt.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketMessageBrokerConfig  implements WebSocketMessageBrokerConfigurer {
	
	@Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //websocket(客戶端sockjs與服務器)建立連接端點名,客戶端需要註冊這個端點進行鏈接,withSockJS允許客戶端利用sockjs進行瀏覽器兼容性處理
		registry.addEndpoint("/sockjs/endpoint").setAllowedOrigins("*").withSockJS(); 
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
    	registry.enableSimpleBroker("/topic");//這句表示在topic和user這兩個域上可以向客戶端發消息;
    	registry.setUserDestinationPrefix("/user/");//這句表示給指定用戶發送(一對一)的主題前綴是“/user/”;  
    	registry.setApplicationDestinationPrefixes("/sockjs"); //這句表示客戶端向服務端發送時的主題上面需要加"/app"作爲前綴;
    }
    
    @Bean
    public SocketSessionRegistry socketSessionRegistry(){
        return new SocketSessionRegistry();
    }
    @Bean
    public STOMPConnectEventListener stompConnectEventListener(){
        return new STOMPConnectEventListener();
    }

}

PhotoBurst.java

package com.casm.gdt.entriy;

public class PhotoBurst {
	private int id;//第幾片
	private int total;//一共多少片
	private int filesplitsize;//每片大小
	private String name;//上傳的圖片名稱
	private String date;//上傳時間
	private String data;//數據(base64流)
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getTotal() {
		return total;
	}
	public void setTotal(int total) {
		this.total = total;
	}
	
	public int getFilesplitsize() {
		return filesplitsize;
	}
	public void setFilesplitsize(int filesplitsize) {
		this.filesplitsize = filesplitsize;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getData() {
		return data;
	}
	public void setData(String data) {
		this.data = data;
	}
	public String getDate() {
		return date;
	}
	public void setDate(String date) {
		this.date = date;
	}
	
	
}

 SourceMessage.java

package com.casm.gdt.entriy;

public class SourceMessage {
	
	private String photo;
	private String video;
	private String size;
	public String getPhoto() {
		return photo;
	}
	public void setPhoto(String photo) {
		this.photo = photo;
	}
	public String getVideo() {
		return video;
	}
	public void setVideo(String video) {
		this.video = video;
	}
	public String getSize() {
		return size;
	}
	public void setSize(String size) {
		this.size = size;
	}
	
	
	
}

Base64ToFile.java

package com.casm.gdt.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStream;
import java.io.RandomAccessFile;

import org.springframework.stereotype.Service;

import com.casm.gdt.entriy.PhotoBurst;

import sun.misc.BASE64Decoder;

@Service
public class Base64ToFile {

	/**
	  * base64編碼字符串轉換爲圖片
	  * @param imgStr base64編碼字符串
	  * @param path 圖片路徑
	  * @return
	  */
	 public boolean base64StrToImage(PhotoBurst photoBurst, String path) {
		 if (photoBurst.getData() == null)
			 return false;
		 BASE64Decoder decoder = new BASE64Decoder();
		 try {
		     // 解密
		     byte[] b = decoder.decodeBuffer(photoBurst.getData());
		     // 處理數據
		     for (int i = 0; i < b.length; ++i) {
		    	 if (b[i] < 0) {
		    		 b[i] += 256;
		    	 }
		     }
		     //文件夾不存在則自動創建
		     File tempFile = new File(path);
		     if (!tempFile.getParentFile().exists()) {
		    	 tempFile.getParentFile().mkdirs();
		     }
		     
		     //如果文件存在則在文件指定位置中追加內容
		     if(tempFile.exists()) {
		    	  RandomAccessFile raf=new RandomAccessFile(tempFile, "rw");
	              //將寫文件指針移到指定位置。
		    	  raf.seek((int)((photoBurst.getId()-1)*photoBurst.getFilesplitsize()*0.75));
	              raf.write(b);
	              raf.close();
		     }else {
		    	 //如果文件不存在新建
		    	 OutputStream out = new FileOutputStream(tempFile);
			     out.write(b);
			     out.flush();
			     out.close(); 
		     }
		     return true;
		 } catch (Exception e) {
			 System.out.println(e.getMessage());
		     return false;
		 }
	 }
}

 

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