今天整理一下微信开发中遇到的图片和附件的上传问题。
开发环境参考:微信开发(一)--分享接口 点击打开链接
由于是基于weixin-java-tools 封装的java sdk,所以在微信底层处理上我们可以直接调用WxMpService.
一.数据准备:
进入页面前,根据条件查询相应的图片附件列表(已有数据时进行展示,没有数据可以忽略):
//查询图片数据
List imgList = fileModelService.loadFileModelsByBFTT(11);
//查询附件数据
List attachmentFileList = fileModelService.loadFileModelsByBFTT(11);
二.页面准备:
jspye页面设置上传按钮,遍历读取图片列表
-
附件上传:
三.初始化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= 6 ){
layer.msg("最多允许上传6张图片!");
return;
}
var imgHtml = "";
imgHtml += "";
imgHtml += " ";
$(".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= 6 ){
layer.msg("最多允许上传6份附件!");
return;
}
//上传文件
$.ajaxFileUpload({
url: basePath+"/fileupload/uploadAttachment.do", //文件上传到哪个地址,告诉ajaxFileUpload
data:{"bussinessId":bussinessId,"id":id},
secureuri: false, //一般设置为false
fileElementId: 'attachmentFile', //文件上传控件的Id
dataType: 'json', //返回值类型 一般设置为json
success: function (data, status){//服务器成功响应处理函数
if(data.state == 200){
var imgHtml = "";
imgHtml += ""+data.data[1]+"";
imgHtml += "";
imgHtml += " ";
$(".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 fileModelStorelist = new ArrayList();
for (int i=0;i 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;
}
}
学习在于不断地探索、思考和总结记录,欢迎喜欢的朋友们在下方留言,与君共同进步!