微信开发(二)--上传图片和附件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36500554/article/details/80769728

      今天整理一下微信开发中遇到的图片和附件的上传问题。

      开发环境参考:微信开发(一)--分享接口 点击打开链接

      由于是基于weixin-java-tools 封装的java sdk,所以在微信底层处理上我们可以直接调用WxMpService.

      .数据准备:

           进入页面前,根据条件查询相应的图片附件列表(已有数据时进行展示,没有数据可以忽略):

	           //查询图片数据  
		List<FileModel> imgList = fileModelService.loadFileModelsByBFTT(11);
		   //查询附件数据
		List<FileModel> attachmentFileList = fileModelService.loadFileModelsByBFTT(11);
		

      二.页面准备:    

            jspye页面设置上传按钮,遍历读取图片列表   

    <!-- 图片上传 -->   
				 <div class="form-group">
				    <div class="input-group">
				       <div class="input-group-addon "><span style="color:red;"> </span>图片上传:</div>
				       <input type="hidden" name="fileIds" id="fileIds">
				       <div class="input-group-addon">
				       	
				       				<a href="javascript:void(0)" onclick="chooseImage('${basePath }','${id}');">
						       			<span class="glyphicon glyphicon-plus"></span>
						       		</a>
				       
				       </div>
				    </div>
				  </div>
				  
				  <!-- 缩略图 -->
				  <ul class="body-img-ul">
				  		<c:forEach items="${imgList}" var="v" varStatus="sta">
				  			<li style="background-image:url('${simplePath }${v.revealpath }')" 
				  				onclick="previewImage('${simplePath }${v.revealpath }');">
				  		
					       		<i class="del_icon" onclick="deleteImage('${v.id }',this,'${basePath }')"></i>
		    	            </li>
				  		</c:forEach>
				  </ul>
				   <!-- 附件上传 --> 
				   <div class="form-group">
				    <div class="input-group">
				       <div class="input-group-addon "><span style="color:red;"> </span>附件上传:</div>
				       <div class="input-group-addon">
				       		<input type="hidden" name="attachmentIds" id="attachmentIds">
				       		
					       				<span class="glyphicon glyphicon-plus">
					       					<input type="file" class="attachmentFile" name="attachmentFile" id="attachmentFile"
						       				 onchange="uploadAttachment('${basePath }','${id}');"/>
					       				</span>
				       </div>
				    </div>
				  </div>
				  <!-- 附件 -->
				  <ul class="body-file-ul">
				  		<c:forEach items="${attachmentFileList }" var="v" varStatus="sta">
		    	            <li>
					  			<a href="${simplePath }${v.revealpath }">
					  				<c:choose>
			              		 		<c:when test="${fn:length(v.filename) < 20 }">
			              		 			${v.filename }
			              		 		</c:when>
			              		 		<c:otherwise>
			              		 			${fn:substring(v.filename,0,20) }....${v.extname }
			              		 		</c:otherwise>
			              		 	</c:choose>
					  			</a>
					
					       				<i class="del_icon" onclick="deleteImage('${v.id }',this,'${basePath }')"></i>
		    	            </li>
				  		</c:forEach>
				  </ul>
				<!-- 附件上传 -->  
				    

     三.初始化jssdk:  

          controller

@Controller
@RequestMapping("jssdk")
public class WeXinJsSdkController {
	
	@Autowired
	private WxMpService wxMpService;
	
	@RequestMapping(value = "/config", method = RequestMethod.GET)
	@ResponseBody
	public WxJsapiSignature wxJsSdkConfig(HttpServletRequest request,String url) {
		try {
			WxJsapiSignature wxJsapiSignature = wxMpService.createJsapiSignature(url);
			return wxJsapiSignature;
		} catch (WxErrorException e) {
			return null;
		}
	}
	  
}
  js请求获取config 参数 
	/* 初始化jssdk */
	$.get("${basePath}/jssdk/config.do",{url:window.location.href},function(data,status){
		if(status == "success"){
			wx.config({
			    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
			    appId: data.appId, // 必填,公众号的唯一标识
			    timestamp: data.timestamp, // 必填,生成签名的时间戳
			    nonceStr: data.nonceStr, // 必填,生成签名的随机串
			    signature: data.signature,// 必填,签名,见附录1
			    jsApiList: ['chooseImage', 'uploadImage', 'downloadImage', 'previewImage'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
			 
			});
			wx.ready(function(){
				//layer.msg("jssdk初始化成功");
			    // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,
			    //所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
			});
			wx.error(function(res){
			    // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,
			    //也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
				layer.msg(res);
			});
		}
		},"json");

  js 配置

    1. chooseImage    手机选择或拍摄图片 
    2. uploadImage    上传图片到微信服务器
    3. downloadImage  下载图片到本地

    previewImage   本地图片预览 


	
	//微信sdk上传图片------------------------
var images = {
	    localIds: [],
	    serverIds: [],
	  }; 
function chooseImage(basePath,id){
	wx.chooseImage({
	    count: 6, // 默认9
	    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
	    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
	    success: function (res) {
	    	images.localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
	    	//显示缩略图
	        for(var i=0;i<images.localIds.length;i++){
	        	var liLength = $(".body-img-ul li").length;
	        	if(liLength >= 6 ){
	        		layer.msg("最多允许上传6张图片!");
					return;
		        }
	        	var imgHtml = "<li style=\"background-image:url('"+images.localIds[i]+"')\"";
	        		   imgHtml += "onclick=\"previewImage('"+images.localIds[i]+"')\">";
	        		   imgHtml += "<i class=\"del_icon\"></i>";
	        		   imgHtml += "</li>";
	  				
	        	$(".body-img-ul").append(imgHtml);
		    }
		    //递归的上传图片
	        syncUpload(images.localIds,id);
	    }
	});
}
//将微信服务器的图片下载到本地
var syncUpload = function(localIds,id){
	var localId = localIds.pop();
	//上传图片到微信服务器
    wx.uploadImage({
        localId: localId, // 需要上传的图片的本地ID,由chooseImage接口获得
        isShowProgressTips: 1, // 默认为1,显示进度提示
        success: function (res) {
        	images.serverIds.push(res.serverId); // 返回图片的服务器端ID
            if(localIds.length > 0){
            	syncUpload(localIds,id);  
            }else if(images.localIds.length == 0){
            	var serverids = images.serverIds.join(',');
            	$.post(
            		basePath+"/fileupload/uploadImg.do",
            		{"serverIds":serverids,"id":id}
            		,function(data,status){
        			if(status == "success"){
        				images.serverIds = [];
        				//存储文件id到页面
        				setFileIds(data.join(','));
        				
        				var tempLen = $(".del_icon").length;
        				var dataLen = data.length;
        				var del_index;
        				var del_id;
        				for(var i = 1;i<dataLen+1;i++){
        					del_index = tempLen-i;
        					del_id = data[i-1];
        					addDeleteEvent(del_index,del_id,basePath);
        				}
        				layer.msg("上传成功!");
        			}
        	  },"json");
            }
        }
    });
 }
//添加事件
function addDeleteEvent(del_index,del_id,basePath){
	$(".del_icon").eq(del_index).click(function(e){
		deleteImage(del_id,this,basePath);
		window.event.cancelBubble = true;
	});
}
//添加上传的filemodeID
function setFileIds(fildIds){
	var temp = $("#fileIds").val();
	if(temp == ""){
		 $("#fileIds").val(fildIds)
	}else{
		$("#fileIds").val(temp+","+fildIds)
	}
}
//预览图片
function previewImage(url){
	document.write("url----"+url);
	 wx.previewImage({
         current: url, // 当前显示图片的http链接
         urls: [url] // 需要预览的图片http链接列表
	 });
}
//异步删除图片
function deleteImage(id,obj,basePath){
	$.ajax({
		  type: 'POST',
		  url: basePath+"/fileupload/deleteFile.do",
		  data:{"id":id},
		  dataType: 'json',
		  success: function(data){
			 if(data.state == 200){
				layer.msg("删除成功!");
				 //移除对应数据
				 $(obj).parent()[0].remove();
			 }else{
				 layer.msg("删除失败!");
			 }
		  }
		});
	 window.event.cancelBubble = true;
}
//微信sdk上传图片------------------------
//上传附件
function uploadAttachment(basePath,id) {
   //限制数量
	var liLength = $(".body-file-ul li").length;
	if(liLength >= 6 ){
		layer.msg("最多允许上传6份附件!");
		return;
    }
   //上传文件
   $.ajaxFileUpload({
       url: basePath+"/fileupload/uploadAttachment.do", //文件上传到哪个地址,告诉ajaxFileUpload
       data:{"bussinessId":bussinessId,"id":id},
       secureuri: false, //一般设置为false
       fileElementId: 'attachmentFile', //文件上传控件的Id  <input type="file" id="fileUpload" name="file" />
       dataType: 'json', //返回值类型 一般设置为json
       success: function (data, status){//服务器成功响应处理函数
    	   if(data.state == 200){
    		   var imgHtml = "<li>";
    		   imgHtml += "<a href=\""+basePath+data.data[2]+"\">"+data.data[1]+"</a>";
    		   imgHtml += "<i class=\"del_icon\" onclick=\"deleteImage('"+data.data[0]+"',this,'"+basePath+"')\"></i>";
    		   imgHtml += "</li>";
    		   $(".body-file-ul").append(imgHtml)
    		   //存储文件id到页面
    		   setFileIds(data.data[0]);
    	   }
		   layer.msg(data.msg);
       	}
       });
   };
	
.后台配置文件名称,设置本地存储路径,把相应数据存储到本地:  

@Controller
@RequestMapping("/fileupload")
public class FileUploadController {
	
	public String prefix ="yongjun/upload/";
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private WxMpService wxMpService;
	@Autowired
	private UsersService usersService;
	@Autowired
	private FileModelService fileModelService;
	@Value(value = "#{resourceProperties['uploadUrl']}")
	private String uploadUrl;
	
	@RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
	@ResponseBody
	public String[] uploadImg(String serverIds,BigDecimal id,HttpServletRequest request){
		
		String[] result;
		//获取当前用户
		CurrentUser currentUser = usersService.getCurrentUser(request);
		try {
			String[] serverId_arr = serverIds.split(",");
			if(serverId_arr != null && currentUser != null){
				//图片存储
				List<FileModel> fileModelStorelist = new ArrayList<FileModel>();
				for (int i=0;i<serverId_arr.length;i++) {
					File file = wxMpService.getMaterialService().mediaDownload(serverId_arr[i]);
					String filePath = FileUploadUtil.uploadImg(file, uploadUrl, currentUser);
					//文件模型数据
					FileModel fileModel = new FileModel();
					fileModel.setCreatedTime(new Date());
					byte disabled = 0;
					fileModel.setDisabled(disabled);
					fileModel.setFilename(file.getName());
					fileModel.setRealname(file.getName());
					fileModel.setExtname(filePath.substring(filePath.lastIndexOf(".")+1));
					fileModel.setFilepath(filePath);
					fileModel.setRevealpath(filePath.replace("C:\\crm2009\\upload", "/myImg").replace("\\", "/"));
					fileModel.setFiletype("image");
					
					fileModelStorelist.add(fileModel);
				}
				result = fileModelService.storeFileModelList(fileModelStorelist);
				return result;
			}else{
				logger.info("当前用户不存在!!");
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("下载文件失败!!"+e.getClass());
			return null;
		}
		
		
	}
	@RequestMapping(value = "/uploadAttachment", method = RequestMethod.POST)
	@ResponseBody
	public ResultData uploadAttachment(BigDecimal bussinessId,BigDecimal id,HttpServletRequest request,MultipartFile attachmentFile){
		
		//判断文件类型
		String originalFilename = attachmentFile.getOriginalFilename();
		String[] imagType={".jpg",".png",".bmp",".gif"};
		List<String> imagTypeList = Arrays.asList(imagType);
		if(imagTypeList.contains(originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase())){
			return ResultData.error("无法上传图片!");
		}
		String[] result = new String[3];
		//获取当前用户
		CurrentUser currentUser = usersService.getCurrentUser(request);
		try {
			if(currentUser != null){
				//上传文件
				String filePath = FileUploadUtil.uploadFile(attachmentFile, uploadUrl, currentUser);
				//文件模型数据
				FileModel fileModel = new FileModel();
				fileModel.setCreatedTime(new Date());
				byte disabled = 0;
				fileModel.setBussinessid(bussinessId);
				fileModel.setDisabled(disabled);
				fileModel.setFilename(originalFilename);
				fileModel.setRealname(filePath.substring(filePath.lastIndexOf("/")+1));
				fileModel.setExtname(filePath.substring(filePath.lastIndexOf(".")+1));
				fileModel.setFilepath(filePath);
				fileModel.setRevealpath(filePath.replace("C:\\crm2009\\upload", "/myImg").replace("\\", "/"));
				fileModel.setFiletype("attachment");
				fileModelService.storeFileModel(fileModel);
				
				result[0] = fileModel.getId().toString();
				result[1] = fileModel.getFilename();
				result[2] = fileModel.getRevealpath();
				return ResultData.ok(result, "上传成功!");
			}else{
				logger.info("当前用户不存在!!");
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("下载文件失败!!"+e.getClass());
			return null;
		}
		
		
	}
	
	@RequestMapping(value = "/deleteFile", method = RequestMethod.POST)
	@ResponseBody
	public ResultData deleteFile(BigDecimal id){
		fileModelService.deleteFileModel(id);
		return ResultData.ok();
	}
	
}
.设置 文件转接工具类:

     

public class FileUploadUtil {
	/**
	 * 上传文件
	 * @param file 源文件
	 * @param uploadUrl 上传地址
	 * @param currentUser 当前用户
	 * @param fileType 
	 * @return
	 */
	public  static String uploadImg(File file,String uploadUrl,CurrentUser currentUser) {
		//处理待写入的位置
		if(currentUser != null){
			uploadUrl += "\\image\\" +currentUser.getLoginName().toString();
		}
		File uploadPosition = new File(uploadUrl);
		if(!uploadPosition.exists()){
			//文件路径不存在,则创建
			uploadPosition.mkdirs();
		}
		if (file.renameTo(new File(uploadPosition + "\\" + file.getName()))) {
            System.out.println("File is moved successful!");
        } else {
            System.out.println("File is failed to move!");
        }
		return uploadPosition + "/" + file.getName();
	}
	public  static String uploadFile(MultipartFile file,String uploadUrl,CurrentUser currentUser) throws UnsupportedEncodingException {
		//处理待写入的位置
		if(currentUser != null){
			uploadUrl += "\\attachment\\" +currentUser.getLoginName().toString();
		}
		File uploadPosition = new File(uploadUrl);
		if(!uploadPosition.exists()){
			//文件路径不存在,则创建
			uploadPosition.mkdirs();
		}
		String originalFilename = file.getOriginalFilename();
		String realName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
		try {
			file.transferTo(new File(uploadPosition + "\\" +  realName));
			System.out.println("File is moved successful!");
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
			System.out.println("File is failed to move!");
		}
		return uploadPosition + "/" + realName;
	}
} 
   学习在于不断地探索、思考和总结记录,欢迎喜欢的朋友们在下方留言,与君共同进步!







猜你喜欢

转载自blog.csdn.net/qq_36500554/article/details/80769728
今日推荐