H5上传图片【流方法】

一、班级通知。

1、有时候可能会出现Base64不能预览和上传图片的情况,此时可以用流的方法。

① 引入JS【在下载中心查询】:

<script src="${base}/res/js/yxy.jssdk-1.1.1.js?v=12dfadfdasdad" type="text/javascript" charset="utf-8"></script>

② HTML:

<div class="add_picture_div">
				<a id="addPicButton" href="#" class="add_picture" onclick="javascript:addPicture();">
					<img src="${base}/res/images/add.png">
				</a>
			</div>

③ 函数方法【数据库对应字段类型为longtext,在Java中为LONGVARCHAR】:

var myHtml="";
		function addPicture(){
			var imgCount = $(".add_picture").length;
			if(imgCount >= 8){
				$(".addPicButton").remove();
			}
			yxy.selectImage({
				success:function(data){
					var dataFilePath = data.filePath
					mui.post('${base}/classedit/notice/uploadImg?userInfoId=${userInfoId}',{
						imgData:dataFilePath
						},function(data){
							/* var imgStr = "<li class='mui-table-view-cell mui-media mui-col-xs-4'><a href='#'>"
									+ '<img class="add_picture" style="max-width:100%" src="/classSpaceAlbum'+data.imgPath+'"/></a></li>'; */
							var imgStr = "<a href='#'>"+'<img class="add_picture" style="max-width:100%" src="/classSpaceAlbum'+data.imgPath+'"/></a>';
							myHtml += "<br><p style='text-align:center;'><img style='max-width:100%' src='"+data.imgDataFile+"'/></p>";
							$(".add_picture_div").append(imgStr);
						},'json'
					);
				},
				error:function(data){
					$(".result").html("error");
				}
			});
		}

2、Controller层:

// 选择照片【每次选择一张,可以选择多张】
	@RequestMapping("/uploadImg")
	@ResponseBody
	public JSONObject uploadImg(@RequestParam(value = "userInfoId") String userInfoId,
			@RequestParam(value = "imgData") String imgData) {
		JSONObject obj = new JSONObject();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		String photoId = UuidUtil.getUuid();
		String absolutePath = AlbumCommonConstants.IMG_UPLOAD_PATH + "/" + userInfoId + "/" + "/"
				+ sdf.format(new Date());
		String[] imgRealData = imgData.split(",");
		byte[] imgByte = Base64.decodeBase64(imgRealData[1]);
		for (int i = 0; i < imgByte.length; ++i) {
			if (imgByte[i] < 0) {// 调整异常数据
				imgByte[i] += 256;
			}
		}
		try {
			File targetFile = new File(absolutePath);
			if (!targetFile.exists())
				targetFile.mkdirs();
			OutputStream out = new FileOutputStream(absolutePath + "/" + photoId + ".jpg");
			out.write(imgByte);
			out.flush();
			out.close();
		} catch (IOException e) {
			logger.error("上传图片失败!", e);
			e.printStackTrace();
		}
		obj.put("imgPath", "/" + userInfoId + "/" + "/" + sdf.format(new Date()) + "/" + photoId + ".jpg");
		obj.put("imgDataFile", imgData);
		obj.put("success", "success");
		return obj;
	}

3、上传照片:

var params = "";
			$("#cls").find("span").each(function(){
				if($(this).hasClass("classIdSpan")){
					params += "&ownerId="+$(this).attr("id");
				}
			});
			var listTitle = $("#title").val();
$.ajax({
				url:'${base}/classedit/notice/noticePublish?listTitle='+listTitle+params,
				type:"post",
				data:{
					/* ownerId:$("#clsId").val(),		// 班级ID
					listTitle:$("#title").val(), */
					needFeedBack:needFeedBack,
					txt:$("#container").val()+myHtml,
					trans:$("#container").val()
				},
				success:function(result){
					console.info(result);
					if(result.status == true){
						window.location.href='toNoticeListPage?userId=${userInfoId!'' }';
					}else{
						alert("发布失败!");
						window.location.reload();
					}
				}
			});

二、班级相册。

1、函数方法:

function addPicture(){
			var imgCount = $(".uploadImgClass").length;
			if(imgCount >= 8){
				$(".addPicButton").remove();
			}
			yxy.selectImage({
				success:function(data){
					var dataFilePath = data.filePath
					mui.post('${base}/classedit/albums/uploadImg?zoneId=${zoneId}&albumsId=${albumsId}',{
						imgData:dataFilePath
						},function(data){
							var imgStr = "<li class='mui-table-view-cell mui-media mui-col-xs-4'><a href='#'>"
									+ '<img class="uploadImgClass" style="max-width:100%" src="/classSpaceAlbum'+data.imgPath+'"/></a></li>';
							$("#addPhoto").append(imgStr);
						},'json'
					);
				},
				error:function(data){
					$(".result").html("error");
				}
			});
		}

2、Controller层:

// 选择照片
	@RequestMapping("/uploadImg")
	@ResponseBody
	public JSONObject uploadImg(@RequestParam(value="zoneId") String zoneId,
			@RequestParam(value="albumsId") String albumsId,
			@RequestParam(value = "imgData") String imgData){
		JSONObject obj = new JSONObject();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		String photoId = UuidUtil.getUuid();
		String absolutePath = AlbumCommonConstants.IMG_UPLOAD_PATH + "/" + zoneId + "/" + albumsId + "/" + sdf.format(new Date());
		String[] imgRealData = imgData.split(",");
		byte[] imgByte = Base64.decodeBase64(imgRealData[1]);
		for(int i = 0; i<imgByte.length; ++i) {
            if(imgByte[i]<0) {//调整异常数据  
                imgByte[i] += 256;  
            }  
        }
		try {
			File targetFile = new File(absolutePath);
			if(!targetFile.exists())
				targetFile.mkdirs();
			OutputStream out = new FileOutputStream(absolutePath + "/" + photoId + ".jpg");
			out.write(imgByte);
	        out.flush();  
	        out.close();
		} catch (IOException e) {
			logger.error("上传图片失败!", e);
			e.printStackTrace();
		}
		obj.put("imgPath", "/" + zoneId + "/" + albumsId + "/" + sdf.format(new Date())  + "/" + photoId + ".jpg");
		obj.put("imgDataFile", imgData);
		obj.put("success", "success");
		return obj;
	}

3、点击上传操作。

① JS:

// 点击上传操作
		function upload(){
			if($("#selectAlbum").html()=="请选择相册"){
				return alert("请先选择要上传图片的相册!");
			}
			var imgUrl = new Array();
			$(".uploadImgClass").each(function(){
				var imgSrc = $(this)[0].src;
				imgUrl.push(imgSrc);
			});
			if(imgUrl.length==0){
				return alert("请先选择需要上传的图片!");
			}
			$("#huanzhong").css("display","block");
			mui.post('${base}/classedit/albums/toUploadOperation?zoneId=${zoneId}&albumsId=${albumsId}',{
			 	imgUrl:imgUrl
				},function(data){
					if(data.status==200){
						window.location.href='toClassAlbum';
					}else{
						alert("上传失败!");
						window.location.reload();
					}
				},'json'
			);
			/* var formData = new FormData();
			$.each(uploadFile_add.uploadFileArray,function(k,v){
				formData.append("fileList",v);
			}); */
			/* $.ajax({
				url:"${base}/classedit/albums/toUploadOperation?zoneId=${zoneId}&albumsId=${albumsId}",
				type:"post",
				data: formData,
				contentType:false,
				processData:false,
				success:function(result){
					if(result.status=="200"){
						alert(result.msg);
						window.location.href='toClassAlbum';
					}else if(result.status=="400"){
						alert(result.msg);
						window.location.reload();
					}
				}
			}); */
			/* var url = "${base}/classedit/albums/toUploadOperation?zoneId=${zoneId}&albumsId=${albumsId}";
			var xhr = new XMLHttpRequest();
			// 请求类型【true为异步处理请求,false为同步处理请求】
			xhr.open("post", url, true); 
			// 上传进度
			xhr.upload.addEventListener("progress", function(result) {  	  
			    if (result.lengthComputable) {  
			        var percent = (result.loaded / result.total * 100).toFixed(2);   
			    }  
			}, false); 
			// 事件监听
			xhr.addEventListener("readystatechange", function() {  
			    var result = xhr;  
			    if (result.status!=200) {  
			    	console.log('上传失败', result.status, result.statusText, result.response); 
			    	alert(JSON.parse(result.responseText).msg);
			    	window.location.reload();
			    }else if(result.readyState==4) { 
			    	console.log('上传成功', result); 
			    	alert(JSON.parse(result.responseText).msg);
			    	window.location.href='toClassAlbum';
			    }
			});
			// 开始上传
			xhr.send(formData); */
		}

② Controller表现层:

@RequestMapping(value="toUploadOperation")
	@ResponseBody
	public Map<String,Object> uploadOperation(
			@RequestParam(value="zoneId") String zoneId,@RequestParam(value="albumsId") String albumsId,
			@RequestParam(value = "imgUrl[]", required=false) String imgUrl[],
			HttpServletRequest request,HttpServletResponse response) throws Exception{
		Map<String,Object> map = Maps.newHashMap();
		String userId = user.getUserId();
		String accountName = zoneDataService.getZoneDataByOwnerId(userId).getOwnerName();
		String content = gzoneAlbumsService.selectGzoneAlbumsByAlbumId(albumsId).getAlbumsName();
		//图片地址为: 项目名称 /classId or personId/相册名称/年/月/日/图片名称
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		String realOfImagePath = AlbumCommonConstants.IMG_UPLOAD_PATH + "/" + zoneId + "/" + albumsId + "/" + sdf.format(new Date());
		String fileRealName = "",fileSuffixName = "";
		for(int i=0;i<imgUrl.length;i++){
			String photoId = imgUrl[i].substring(imgUrl[i].lastIndexOf("/")+1, imgUrl[i].lastIndexOf("."));
			SimpleDateFormat sdfPlus = new SimpleDateFormat("yyyy/MM/dd/hh/mm/ss/SSS");
			fileRealName = "classAlbum" + sdfPlus.format(new Date());
			fileSuffixName = "jpg";
			File targetFile = new File(realOfImagePath, photoId + "." + fileSuffixName);
			if(!targetFile.exists())
				targetFile.mkdirs();
			// 添加照片信息
			GzonePhoto gzonePhoto = new GzonePhoto();
			gzonePhoto.setPhotoId(photoId);
			gzonePhoto.setPhotoName(fileRealName);
			gzonePhoto.setAlbumsId(albumsId);
			gzonePhoto.setPath("/" + zoneId + "/" + albumsId + "/" + sdf.format(new Date())  + "/" + photoId + ".jpg");
//			gzonePhoto.setPath(AlbumCommonConstants.IMG_UPLOAD_FLECTION_PATH + "/" + zoneId + "/" + albumsId + "/" + sdf.format(new Date())  + "/" + photoId + "." + fileSuffixName);
			gzonePhoto.setCommend(0);		 // 点赞数
			gzonePhoto.setEvalCount(0); 	 // 评论数
			gzonePhoto.setUploadTime(new Date());
			gzonePhoto.setCreatorName(zoneDataService.getZoneDataByOwnerId(userId).getOwnerName());
			gzonePhoto.setCreatorId(userId);
			gzonePhoto.setSort(1);
			gzonePhotoService.insertGzonePhoto(gzonePhoto);
			// 添加日志信息
			GzoneOplog gzoneOplog = new GzoneOplog();
			gzoneOplog.setOpId(UuidUtil.getUuid());
			gzoneOplog.setOpTime(new Date());
			gzoneOplog.setAccountId(userId);
			gzoneOplog.setAccountName(accountName);
			gzoneOplog.setOpType("upload");
			gzoneOplog.setOpName("移动端上传照片");
			gzoneOplog.setObjectId(photoId);		// 这里的ObjectId是照片photoId
			gzoneOplog.setObjectType("photo");
			gzoneOplog.setContent(content);
			gzoneOplog.setRemark(accountName + "发布了一条相册动态!");
			gzoneOplog.setEvalCount(0);
			gzoneOplog.setZanCount(0);
			gzoneOplog.setViewCount(0);
			gzoneOplog.setZoneId(zoneId);
			gzoneOplogService.addGzoneOplog(gzoneOplog);
		}
		GzoneAlbums gzoneAlbums = gzoneAlbumsService.selectGzoneAlbumsByAlbumId(albumsId);		// 指定相册
		int sum = imgUrl.length;
		sum += gzoneAlbums.getAlbumsTotal();
		gzoneAlbumsService.updateTotalByAlbumIdAndSum(albumsId,sum);
		map.put("success", "success");
		map.put("status", "200");
		map.put("msg", "上传成功!");
		return map;
	}

----- END -----

猜你喜欢

转载自blog.csdn.net/a515557595_xzb/article/details/79441951