實現微信公眾號微信頭像上傳
阿新 • • 發佈:2018-11-08
這次我們做的專案需要實現一個微信公眾號頭像上傳並且剪裁的功能,實在沒有頭緒,之後通過網上搜索和自己的修改實現了一個適合我們這個框架的方法。
首先本次專案我們的頁面用的事velocity框架,頁面程式碼是:
js程式碼如下:<li> <span class="ti"><img src="$tp.headImg"></span> <div class="ci"><span><a href="#" class="ed" id="diyUploadimg">更換頭像</a></span></div> </li>
以上就是此功能的上傳頭像頁面的html與js程式碼,下面是上傳頭像的Java程式碼,<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script> var voice = { localId: '', serverId: '' }; wx.config({ debug: false, appId: '${weixin.appId}', timestamp: '${weixin.timestamp}', nonceStr: '${weixin.nonceStr}', signature: '${weixin.signature}', jsApiList: [ 'chooseImage', 'uploadImage','openLocation','getLocation','scanQRCode','startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'onVoicePlayEnd', 'pauseVoice', 'stopVoice', 'uploadVoice', 'downloadVoice' ] }); wx.ready(function () { // 5 圖片介面 // 5.1 拍照、本地選圖 var images = { localId: [], serverId: [] }; document.querySelector('#diyUploadimg').onclick = function () { alert(1) wx.chooseImage({ count: 1, success: function (res) { images.localId = res.localIds; uploadImg(); } }); }; // 5.3 上傳圖片 function uploadImg() { if (images.localId.length == 0) { alert('請先使用 chooseImage 介面選擇圖片'); return; } var i = 0, length = images.localId.length; images.serverId = []; function upload() { wx.uploadImage({ localId: images.localId[i], success: function (res) { i++; //alert('已上傳:' + i + '/' + length); images.serverId.push(res.serverId); if (i < length) { upload(); }else{ wxImgCallback(); } }, fail: function (res) { alert(JSON.stringify(res)); } }); } upload(); }; var tag=0; function wxImgCallback() { $.ajax({ type : "get", async : false,//變非同步為同步 url : "wx_uploadImg.html", data : { "imgServerId" : images.serverId[0] }, success : function(data) { window.location.href='/wx/headImg.html?imgurl='+data; tag=1; } }); } });
以上是微信端實現頭像上傳的所有程式碼可能少了一部分,今天時間有限後續補上。下面貼出頭像剪裁程式碼ApiConfig config = new ApiConfig(Constant.appId, Constant.appSecret); // 微信照片上傳功能 String ticket = config.getJsApiTicket(); String code = request.getParameter("code"); String url= baseurl+"/wx/teacherBaseInfo.html";//注意此處路徑需要與本頁面路徑完全一致,如果需要變得 頁面跳轉到此頁面引數也必須保持一致 Weixin w = WeixinUtil.sign(ticket, url); modelMap.addAttribute("weixin", w);
首先是html程式碼:
<div class="container">
<div class="row">
<div class="span12">
<form id="cutImage">
<div class="jc-demo-box">
<img style="width: 300px;height: 300px" src="$!url" id="target" alt="[Jcrop Example]" name="" />
<input type="hidden" name="srcImg" value="$!url"/>
<div style="display: none">
<label>X1 <input type="text" size="4" id="x1" name="x" /></label>
<label>Y1 <input type="text" size="4" id="y1" name="y" /></label>
<label>X2 <input type="text" size="4" id="x2" name="width" /></label>
<label>Y2 <input type="text" size="4" id="y2" name="height" /></label>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="buton">
<a href="#" class="btn btn-no" onclick="fanhui()">取消</a>
<a href="#" class="btn btn-ok" onclick="baoCun()">提交</a>
</div>
</body>
下面是js程式碼:
<script>
function showCoords(c)
{
$('#x1').val(c.x);
$('#y1').val(c.y);
$('#x2').val(c.x2);
$('#y2').val(c.y2);
};
$(function() {
$('#target').Jcrop({
aspectRatio: 1, //選中區域寬高比為1,即選中區域為正方形
bgColor:"#ccc", //裁剪時背景顏色設為灰色
bgOpacity:0.1, //透明度設為0.1
allowResize:true, //不允許改變選中區域的大小
allowMove:true,//是否允許移動選中區域。
setSelect:[0,0,100,100] , //初始化選中區域
onChange: showCoords,
onSelect: showCoords
}
);
});
function baoCun(){
_url = '/wx/cutImage.json';
$.ajax({
cache: true,
type: 'POST',
url: _url,
data: $('#cutImage').serialize(),
success: function(data) {
if(data.code == 0){
alert(data.msg);
if(data.type == 0){
window.location.href="/wx/teacherBaseInfo.html";
}
if(data.type == 1){
window.location.href="/wx/parentBaseInfo.html";
}
}else {
alert(data.msg)
}
}
});
}
function fanhui() {
window.history.back(-1);
}
</script>
最後是Java部分頭像剪裁程式碼:
@RequestMapping("/cutImage.json")
@ResponseBody//注意此處,我用的springboot框架,此方法一定要加上這個註釋,我就是忽略了返回值不能是總是不對腦 殘了
public Map cutImage(ModelMap modelMap, HttpServletRequest request, String srcImg, String destImg, int x, int y, int width, int height){
Map result = new HashMap();
WxUser tp = (WxUser) request.getSession().getAttribute("wxUser");//此處調通後開放
//圖片的相對路徑
String imagPath=request.getParameter("srcImg");
String fileRealPath = request.getSession().getServletContext().getRealPath("/") ;
System.out.println("圖片路徑:"+fileRealPath);
// String fileRealPath="d://";
String newFileName= UUID.randomUUID()+".jpg";
//實際圖片路徑
String img = imagPath.replaceAll(baseurl,"");
String path1=fileRealPath+img;
//裁剪後儲存到伺服器的圖片路徑
String path2=fileRealPath+"upload/weixin/"+newFileName;
System.out.println("圖片路徑:"+path1);
System.out.println("輸出路徑:"+path2);
try{
CutImage(path1, path2, x, y, width, height);
if("0".equals(tp.getType())){
WxUser wxUser = wxUserService.findById(tp.getId().toString());
String url = "/upload/weixin"+path2.substring(path2.lastIndexOf("/"));
wxUser.setHeadImg(url);
wxUserService.update(wxUser);
result.put("type","0");
}else {
WxUserParent wxUserParent = wxUserParentService.findById(tp.getId().toString());
String url = "/upload/weixin"+path2.substring(path2.lastIndexOf("/"));
wxUserParent.setHeadImg(url);
wxUserParentService.update(wxUserParent);
result.put("type","1");
}
result.put("code",0);
result.put("msg","成功");
}catch(Exception e){
result.put("code",1);
result.put("msg","失敗");
}
return result;
}
/**
* @param path1 圖片原路徑
* @param path2 裁剪後儲存的路徑
* @param x x軸
* @param y y軸
* @param w
* @param h
*/
public static void CutImage(String path1,String path2,int x,int y,int w,int h){
FileInputStream fileInputStream=null;
ImageInputStream iis=null;
try {
//讀取圖片檔案,建立檔案輸入流
fileInputStream=new FileInputStream(path1);
//建立圖片的檔案流 迭代器
Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName("jpg");
ImageReader reader=it.next();
//獲取圖片流 建立文圖 檔案流
iis=ImageIO.createImageInputStream(fileInputStream);
//獲取圖片預設引數
reader.setInput(iis, true);
ImageReadParam param=reader.getDefaultReadParam();
//定義裁剪區域
Rectangle rect=new Rectangle(x,y,w,h);
param.setSourceRegion(rect);
BufferedImage bi=reader.read(0,param);
ImageIO.write(bi, "jpg", new File(path2));
} catch (Exception e) {
e.printStackTrace();
System.out.println("裁剪失敗");
}finally{
try {
if(fileInputStream!=null){
fileInputStream.close();
}
if(iis!=null){
iis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上就是我這個功能的程式碼,我只是自己留下以後可能用得到,還少一部分程式碼,有時間我就加上。
補上之前上傳頭像那塊的Java程式碼,之前少弄了那個上傳檔案的程式碼,很關鍵哈哈:
String filetype=".zip|.xls|.xlsx|.doc|.docx|.ppt|.pptx|.jpg|.jpeg|.png|.gif|.rar|.txt|.csv|.pdf|.wps|.dps";
public boolean isfiletype(String suffix){
return filetype.contains(suffix.toLowerCase());
}
@RequestMapping("/uploadfiles.html")
@ResponseBody
public String uploadfile( @RequestParam String fid,HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> m = new HashMap<String, Object>();
try {
//取得上傳的檔案
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
multipartRequest.getParameter("");
MultipartFile file = multipartRequest.getFile(fid);
//取得上傳的檔案
// response.setContentType("text/html");
// response.setCharacterEncoding("UTF-8");
//得到檔名稱
String realFileName = file.getOriginalFilename();
String suffix = realFileName.substring(realFileName.lastIndexOf("."));
//判斷檔案型別是否可用和檔案型別
if (!isfiletype(suffix)) {
m.put("success", false);/** 結果型別 */
m.put("message", "你上傳的檔案型別不正確!");/** 返回訊息 */
m.put("errorCode", 1);/** 錯誤程式碼 */
return RenderUtil.renderJson(CodeConstants.CODE_SUCCESS, m);
}
String fileRealPath = request.getSession().getServletContext().getRealPath("/") + "/upload/";
UUID uuid = UUID.randomUUID();
String randomName = UUID.randomUUID().toString() + suffix;
//判斷資料夾是否存在
File targerFile = new File(fileRealPath);
//判斷是否存在目錄
if (!targerFile.exists()) {
targerFile.mkdirs();
}
//儲存檔案
File uploadFile = new File(fileRealPath + randomName);
FileCopyUtils.copy(file.getBytes(), uploadFile);
DecimalFormat df=new DecimalFormat("######0.00");
long i=file.getSize();
String s=null;
if(i<1024){
s=i+"B";
}else if(i>1024&&i<1048576){
s=df.format((double)i/1024)+"KB";
}else {
s=df.format((double)i/1048576)+"MB";
}
//配置檔案實體資訊
m.put("success", true);/** 結果型別 */
m.put("message", "檔案上傳成功!");/** 返回訊息 */
m.put("filepath", "/upload/" + randomName);/** 返回訊息 */
m.put("filesize",s);/** 返回訊息 */
m.put("errorCode", 0);/** 錯誤程式碼 */
return RenderUtil.renderJson(CodeConstants.CODE_SUCCESS, m);
} catch (IOException e) {
m.put("success", false);/** 結果型別 */
m.put("message", "上傳失敗!");/** 返回訊息 */
m.put("errorCode",1);/** 錯誤程式碼 */
return RenderUtil.renderJson(CodeConstants.CODE_SUCCESS, m);
}
}
這些程式碼不是自己原創,有網上找的有自己專案裡寫好的,分享在這就是為了自己以後找著方便,而且也方便大家。