微信开发 --- 调用微信上传图片接口,并保存到自己的服务器

微信开发 — 调用微信上传图片接口,并保存到自己的服务器

整体思路是这样的:
1.先把手机上的图片上传到微信服务器,然后返回一个图片ID
2.在通过后台根据ID从微信后台拿到流,保存到服务器
前几个步骤在之前的博客上有提到调通wx.config{}
js

$.ajax({
		type : "post",
		url : "wx/sys.do", //之前的博客上有写到
		data : {
			"url" : location.href.split('#')[0]
		},
		dataType : "json",
		success : function(data) {
			wx.config({
				debug : false, // 开启调试模式   
				appId : data.data.appId,
				timestamp : data.data.timestamp,
				nonceStr : data.data.nonceStr,
				signature : data.data.signature,
				jsApiList : [ 'checkJsApi', 'uploadImage', 'chooseImage' ]
			// 必填,需要使用的JS接口列表,所有JS接口列表见附录2 
			});
			wx.error(function(res) {
				alert("出错了:" + res.errMsg);//这个地方的好处就是wx.config配置错误,会弹出窗口哪里错误,然后根据微信文档查询即可。
			});

			wx.ready(function() {
				wx.checkJsApi({
					jsApiList : [ 'chooseImage' ],
					success : function(res) {

					}
				});
			});
			//点击按钮
			$("#scanQRCode").click(function() {
				wx.chooseImage({
					count : 1, // 默认9
					sizeType : [ 'original', 'compressed' ], // 可以指定是原图还是压缩图,默认二者都有
					sourceType : [ 'album', 'camera' ], // 可以指定来源是相册还是相机,默认二者都有
					success : function(res) {
						var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
						localIdArr = localIds;
						uploadImg(localIds);
					}
				});
			});

		}
	});

	var int = 0;
	var serverIdArr = new Array();
	var localIdArr = new Array();
	function uploadImg(localIds) {//上传成功,微信服务器会返回一个本地ID,可以预览
		wx.uploadImage({//根据本地ID获得微信服务器ID
			localId : localIds[int].toString(), // 需要上传的图片的本地ID,由chooseImage接口获得
			isShowProgressTips : 1, // 默认为1,显示进度提示
			success : function(res) {
				var serverId = res.serverId; // 返回图片的服务器端ID
				var id = $('#id').val();//id
				$.ajax({
					type : "post",
					//这个方法很重要
					url : "wx/upload.do?mediaId=" + serverId + "&id=" + id,//mediaId这个就是微信返回的id传到后台
					data : {
					//data: {"mediaId": serverId},  
					},
					dataType : "json",
					success : function(msg) {
						if (msg.code == 1) {
							top.layer.msg("上传成功!", {
								icon : 6
							});
							location.reload();
						} else {
							lock = true;
							top.layer.msg(msg.msg, {
								icon : 5
							});
						}
					}
				});

			}
		});
	}

jsp
因为框架不同 样式可能不太一样
我这个上传成功后刷新页面从服务器取一下上传的图片

<div class="layui-input-block" style="margin-top: 10px; margin-bottom: 10px; display: block;" id="divy">
			<img <c:if test="${url.url == null}">src="images/null.jpg" </c:if> src="/${url.url}" width="160px" height="150px" />
</div>
<div class="layui-input-block" style="margin-top: 10px; margin-bottom: 10px;">
			<button class="layui-btn layui-btn-normal" id="scanQRCode" style="text-align: center; background-color: #ff4e00; width: 160px;">上传微信二维码</button>
</div> 

Controller

/**
	 * @Method 微信图片下载到服务器
	 * @author 
	 * @throws Exception
	 * @createTime
	 */
	@ResponseBody
	@RequestMapping("upload")
	public JsonBean upload(String mediaId, HttpServletRequest servletRequest, HttpServletRequest request, int id) throws Exception {
		InputStream input = null;
		FileOutputStream output = null;
		try {
		// 从微信获取的流,这个utils就是根据返回mediaId后去流的
			input = picDownload.getInputStream(mediaId);
			String path = "qr";
			File folder = new File(uploadFilePath + path);
			if (!folder.exists()) {
				folder.mkdirs();
			}

			File targetFile = new File(folder, new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".jpg");
			output = new FileOutputStream(targetFile);
			IOUtils.copy(input, output);
            //上边就是把图片保存到服务器里
            //下边是数据库的一些操作
			// 如果数据库有就删除
			QrMe qrMe = qrMeService.selectTeacherId(id);
			if (qrMe != null) {
				qrMeService.deleteUrl(id);
				new File(uploadFilePath + qrMe.getUrl()).delete();
			}

			// 添加数据库
			QrMe newQrMe = new QrMe();
			newQrMe.setUrl(path + "/" + targetFile.getName());
			newQrMe.setTeacherid(id);
			return qrMeService.insertQR(newQrMe);
		} finally {
			IOUtils.closeQuietly(input);
			IOUtils.closeQuietly(output);
		}
	}

utils

package com.admin.commons.utils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class PicDownload {

   //微信接口 
	@Autowired
	private WeiXinUtils weiXinUtils;
	
	/**
	 * 根据文件id下载文件
	 * 
	 * @param mediaId 媒体id
	 * @throws IOException
	 * @throws Exception
	 */
	public InputStream getInputStream(String mediaId) throws IOException {
		InputStream is = null;
		String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + weiXinUtils.getAccessToken() + "&media_id=" + mediaId;  根据AccessToken获取media

		try {
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET"); // 必须是get方式请求
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
			System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
			http.connect();
			is = http.getInputStream();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return is;
	}

	/**
	 * 获取下载图片信息(jpg)
	 * 
	 * @param mediaId 文件的id
	 * @throws Exception
	 */

	public void saveImageToDisk(String mediaId) throws Exception {
		InputStream inputStream = getInputStream(mediaId);
		byte[] data = new byte[1024];
		int len = 0;
		FileOutputStream fileOutputStream = null;
		try {
			fileOutputStream = new FileOutputStream("test1.jpg");
			while ((len = inputStream.read(data)) != -1) {
				fileOutputStream.write(data, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (fileOutputStream != null) {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

刚开始接触这个功能,在网上找了很多资料踩了很多坑,图片不是直接上传到服务器的,而是先上传到微信的服务器,然后再下载到自己的服务器
前台我用的是layui框架

猜你喜欢

转载自blog.csdn.net/weixin_41695965/article/details/83268816