***********微信浏览器里的H5页面******图文发表********
引用js <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
/*点击发表评论*/
var localIdsss;var imgName;
$(".publish,.box img").click(function() {
$.ajax({
type: "GET",
//这里的url是加载微信需要的一些参数(公众号的一些参数)
async: false,
dataType: "json",
data: {
"locationUrl": location.href
},
success: function(config) {
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: config.appId, // 必填,公众号的唯一标识
timestamp: config.timestamp, // 必填,生成签名的时间戳
nonceStr: config.nonceStr, // 必填,生成签名的随机串
signature: config.signature, // 必填,签名,见附录1
jsApiList: ['chooseImage',
'uploadImage',
'downloadImage'
], // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
}
});
wx.ready(function() {
/*拍照或者从相册中选择 */
wx.chooseImage({
count: 1, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function(res) {
var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
uploadImg(localIds);
localIdsss=localIds;
$('.box img').attr('src',localIds);
}
});
function uploadImg(localIds){
/*上传图片接口 */
wx.uploadImage({
localId: localIds.toString(), // 需要上传的图片的本地ID,由chooseImage接口获得
isShowProgressTips: 1, // 默认为1,显示进度提示
success: function(res) {
var serverId = res.serverId; // 返回图片的服务器端ID
$.ajax({
type: "GET",
//这个url是保存微信图片
url: "${basePath}/upload/WxImgSave",async: false,
dataType: "json",
data: {
"serverId":serverId
},
success: function(data){
imgName=data.imageName;
},
error:function(){
alert("error");
}
});
}
});
}
function downloadImg(serverId){
/*下载图片接口 */
wx.downloadImage({
serverId: serverId, // 需要下载的图片的服务器端ID,由uploadImage接口获得
isShowProgressTips: 1, // 默认为1,显示进度提示
success: function(res) {
var localId = res.localId; // 返回图片下载后的本地ID
}
});
}
});
});
//后代保存代码 基于JFinal框架的
package com.activity.common.controller.pc.system;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.activity.common.controller.moblie.base.BaseController;
import com.activity.common.model.system.SystemUser;
import com.activity.common.model.system.UploadImg;
import com.jfinal.kit.PropKit;
import com.jfinal.upload.UploadFile;
import com.web.controller.ControllerPath;
/**
* 上传
*
* @author
*/
@ControllerPath(controllerKey = "/upload")
public class UploadController extends BaseController {
public final Logger log = LoggerFactory.getLogger(UploadController.class);
public static UploadController upload = new UploadController();
private UploadController() {}
public static UploadController getUilt(){return upload;}
//
public String getPlsImg(HttpServletRequest request,String path) throws Exception {
//new一个URL对象
URL url = new URL(path);
//打开链接
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置请求方式为"GET"
conn.setRequestMethod("GET");
//超时响应时间为5秒
conn.setConnectTimeout(5 * 1000);
//通过输入流获取图片数据
InputStream inStream = conn.getInputStream();
//得到图片的二进制数据,以二进制封装得到数据,具有通用性
byte[] data = readInputStream(inStream);
//new一个文件对象用来保存图片,默认保存当前工程根目录
java.util.Random random=new java.util.Random();
int result=random.nextInt(1000);
String imgName = PropKit.use("system.properties").get("upload")+Long.toString(System.currentTimeMillis() / 1000)+result+".jpg";
File imageFile = new File(request.getSession().getServletContext().getRealPath("/")+imgName);
//创建输出流
FileOutputStream outStream = new FileOutputStream(imageFile);
//写入数据
outStream.write(data);
//关闭输出流
outStream.close();
return imgName;
}
//
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//创建一个Buffer字符串
byte[] buffer = new byte[1024];
//每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
//使用一个输入流从buffer里把数据读取出来
while( (len=inStream.read(buffer)) != -1 ){
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
//关闭输入流
inStream.close();
//把outStream里的数据写入内存
return outStream.toByteArray();
}
/**
* 保存微信获取的图片
*/
public void WxImgSave() {
String serverId = getPara("serverId");
String imageName=null;
try {
imageName = saveImageToDisk(serverId);
} catch (Exception e) {
e.printStackTrace();
}
Map<String,String> map=new HashMap<>();
map.put("imageName", imageName);
log.error("******imageName******"+imageName);
renderJson(map);
}
/**
* 获取下载图片信息(jpg) 保存到磁盘里
* @param mediaId 文件的id
* @throws Exception
*/
public String saveImageToDisk(String mediaId) throws Exception {
InputStream inputStream = getInputStream(mediaId);
byte[] data = new byte[1024];
int len = 0;
FileOutputStream fileOutputStream = null;
String imgName=null;
try {
//imgPath=E:\\Tomcat 8.5\\wtpwebapps\\Activity\\upload\\ 这里的路径就是你存放在服务器的路径了
String imgPath=PropKit.use("system.properties").get("imgPath");log.error("imgPath文件路径**********>"+imgPath);
imgName=newId()+".png";
String filePath=imgPath+imgName;
log.error("filePath文件路径**********>"+filePath);
fileOutputStream = new FileOutputStream(filePath);
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();
}
}
}
return imgName;
}
/**
* 删除图片
*/
public void deleteImg(){
String srcUrl = getPara("srcUrl");
String sql="select * from upload_img where img_url = ? ";
List<UploadImg> list = UploadImg.dao.find(sql,srcUrl);
boolean deleteById=false;
for (UploadImg uploadImg : list) {
deleteById = UploadImg.dao.deleteById(uploadImg.getId());
}
if(deleteById){
boolean deleteFile = deleteFile(getRequest(),srcUrl);
log.error("deleteFile**>"+deleteFile);
}
renderJson(deleteById);
}
/**
* 删除单个文件
*
* @param fileName
* 要删除的文件的文件名
* @return 单个文件删除成功返回true,否则返回false
*/
public static boolean deleteFile(HttpServletRequest request,String fileName) {
File file = new File(request.getSession().getServletContext().getRealPath("/")+fileName);
// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
if (file.exists() && file.isFile()) {
if (file.delete()) {
System.out.println("删除单个文件" + fileName + "成功!");
return true;
} else {
System.out.println("删除单个文件" + fileName + "失败!");
return false;
}
}
else {
System.out.println("删除单个文件失败:" + fileName + "不存在!");
return false;
}
}
/**
* 根据文件id下载文件
* @param mediaId媒体id
* @throws Exception
*/
public InputStream getInputStream(String mediaId) {
InputStream is = null;
String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="
+ getAccessToken() + "&media_id=" + mediaId;
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();
// 获取文件转化为byte流
is = http.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
return is;
}
}
//获取微信公众号的配置
/**
* 微信基础配置
*/
public void WxConfig() {
String locationUrl = getPara("locationUrl");
Map<String, String> wxConfigApi = WxConfigApi(locationUrl);
renderJson(wxConfigApi);
}
/**
* 微信js-sdk基本配置参数
*
* @param url
* @return
*/
public Map<String, String> WxConfigApi(String url) {
// jsapi_ticket
JsTicket jsapi_ticket = JsTicketApi.getTicket(JsTicketApi.JsApiType.jsapi);
// 随机串
String nonce_str = create_nonce_str();
// 时间戳
String timestamp = create_timestamp();
// 签名
String signature = "";
// 拼接字符串进行加密,获取签名
String sha1 = "jsapi_ticket=" + jsapi_ticket.getTicket() + "&noncestr=" + nonce_str + "×tamp=" + timestamp
+ "&url=" + url;
try {
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(sha1.getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Map<String, String> configMap = new HashMap<String, String>();
String appId = ApiConfigKit.getApiConfig().getAppId();
configMap.put("url", url);
configMap.put("appId", appId);
configMap.put("jsapi_ticket", jsapi_ticket.getTicket());
configMap.put("nonceStr", nonce_str);
configMap.put("timestamp", timestamp);
configMap.put("signature", signature);
return configMap;
}