1. 程式人生 > >Cropper.js從前臺到後臺的完整例項應用

Cropper.js從前臺到後臺的完整例項應用

外掛很完善,可惜API都是英文看不懂,折騰一天用原demo改出來,這裡記下筆記。

先是html主體

<html lang="zh-CN">
<head>
<link href="../../assets/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="../../assets/plugins/sweetalert/sweetalert.css" rel="stylesheet">
<link href="../../assets/plugins/cropper/cropper.min.css" rel="stylesheet">
</head>
<body>
	<div id="main-wrapper">
		<div class="page-wrapper">
			<div class="container-fluid">
				<div class="card">
					<div class="row p-10">
						<div class="col-md-8 p-b-10">
							<div class="img-container">
								<img id="image" src="${sessionScope.headimageurl}" alt="Picture">
							</div>
						</div>
						<div class="col-md-4 docs-buttons">
							<div class="docs-preview clearfix">
								<div class="img-preview preview-lg"></div>
								<div class="img-preview preview-md"></div>
								<div class="img-preview preview-sm"></div>
								<div class="img-preview preview-xs"></div>
							</div>
							<div class="btn-group">
								<label class="btn btn-primary btn-upload" for="inputImage"> <input type="file"
									class="sr-only" id="inputImage" name="file"
									accept=".jpg,.jpeg,.png,.gif,.bmp,.tiff"> <span
										class="fa fa-upload"> 選擇圖片</span>							
								</label>
							</div>
							<div class="btn-group btn-group-crop">
								<button type="button" class="btn btn-success"
									data-method="getCroppedCanvas"
									data-option="{ "width": 520, "height": 520 }">
									<span>
									</span> <span class="fa fa-search"> 預覽頭像</span>
								</button>
							</div>
							
							<div class="modal fade docs-cropped" id="getCroppedCanvasModal"
								aria-hidden="true" aria-labelledby="getCroppedCanvasTitle"
								role="dialog" tabindex="-1">
								<div class="modal-dialog">
									<div class="modal-content">
										<div class="modal-header">
											<h5 class="modal-title" id="getCroppedCanvasTitle">您的頭像</h5>
											<button type="button" class="close" data-dismiss="modal"
												aria-label="Close">
												<span aria-hidden="true">×</span>
											</button>
										</div>
										<div class="modal-body"></div>
										<div class="modal-footer">
											<button type="button" class="btn btn-secondary"
												data-dismiss="modal">取消</button>
											<button type="button" class="btn btn-info" id="download"
												data-dismiss="modal" onclick="submitForm()">儲存頭像</button>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	<script src="../../assets/plugins/jquery/jquery.min.js"></script>
	<script src="../../assets/plugins/bootstrap/js/popper.min.js"></script>
	<script src="../../assets/plugins/bootstrap/js/bootstrap.min.js"></script>
	<script src="../../assets/plugins/sweetalert/sweetalert.min.js"></script>
	<script	src="../../assets/plugins/sweetalert/jquery.sweet-alert.custom.js"></script>
	<script src="../../assets/plugins/cropper/cropper.js"></script>
	<script src="../../assets/plugins/cropper/main.js"></script>
	<script>
		function submitForm() {
			var cas = $('#image').cropper('getCroppedCanvas', {
				width : 520,
				height : 520
			});// 獲取被裁剪後的canvas  
			var base64 = cas.toDataURL('image/jpeg'); // 轉換為base64
			var data = encodeURIComponent(base64);//作為URI編碼
			$.ajax({
				url : ".uploadHeadImageServlet",
				type : 'POST',
				data : "file=" + data,
				async : true,
				success : function(data) {
					sweetAlert({
						title : "已儲存 !",
						text : "Your headimage file has been updated.",
						type : "success"
					}, function() {
						window.location.href = "myprofile.jsp";
					});
				}
			});
		}
	</script>

</body>
</html>

ajax呼叫servlet

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//獲取使用者ID
		HttpSession session = request.getSession();
		String userid = (String) session.getAttribute("id");
		//收到AJAX的data
		String imagefile = request.getParameter("file");
		//執行圖片上傳方法,並獲得頭像圖片地址		
		String path = uploadbiz.UploadHeadImage(userid, imagefile);		
		//更新session中的頭像地址	
		session.setAttribute("headimageurl", path);		
	}

上傳方法

package sin.service;
import java.io.FileOutputStream;
import sin.dao.UserInfoDao;
import sin.plugins.NewAFileName;
import sun.misc.BASE64Decoder;
@SuppressWarnings("restriction")
public class UploadHeadImageBiz {
	@SuppressWarnings("unused")
	public String UploadHeadImage(String userid, String imagefile) {
		NewAFileName newname = new NewAFileName();
		UserInfoDao userinfodao = new UserInfoDao();
		String path = null;		
        BASE64Decoder decoder = new BASE64Decoder();
        try {
        	//去掉頭data:image/jpeg;base64,
        	String imagebasefile = imagefile.substring(23);
            // Base64解碼
            byte[] bytes = decoder.decodeBuffer(imagebasefile);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 調整異常資料
                    bytes[i] += 256;
                }
            }
            //生成JPEG圖片輸出流,名字,儲存路徑            
            String filename = userid + newname.getFileName();            
            path = "../../../../sin/upload/headimages/" + filename;
            FileOutputStream out = new FileOutputStream(path);
            //更新使用者頭像URL
            Boolean result = userinfodao.updateUserHeadImageById(userid, path);
            out.write(bytes);
            out.flush();
            out.close();
            } catch (Exception e) {
            }
        return path;
    }
}

附手機上使用的效果圖