微信JS-SDK实现上传图片功能
2024-09-12 14:51:14
最近在项目开发中,有一个在微信WEB项目中上传图片的需求,一开始使用了传统的<input type="file">的方式去实现,但是后面发现在使用这种传统模式时会由于手机系统的差异而导致一系列的问题,后改用微信JSSDK的方式来实现,做的过程中也遇到了一些小坑,把经验贴出来给大家分享一下,让大家少走点弯路。
总的来说,利用JSSDK来实现该功能一共分为四步。
1. 调用wx.config(),初始化jssdk的配置,并在jsApiList中配置上传图片需要的四个api('chooseImage','previewImage','uploadImage','downloadImage')
wx.config({
debug : false,
appId : data.appId,
timestamp : data.timestamp,
nonceStr : data.nonceStr,
signature : data.signature,
jsApiList : [
'chooseImage',
'previewImage',
'uploadImage',
'downloadImage'
]
});
2.点击图片时,调用wx.chooseImage(),让用户去选择图片或拍照
function wxChooseImage() {
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function (data) {
var localIds = data.localIds[0].toString();
wxuploadImage(localIds);
}
});
}
3.选择完图片后调用wx.chooseImage(),将图片上传到微信服务器
function wxuploadImage(e) {
layer.load(1);
wx.uploadImage({
localId: e,
isShowProgressTips: 0,
success: function (res) {
fileUpload(res.serverId);
}
});
}
4.利用mediaId将图片从微信服务器下载到本地或项目的图片服务器路径下,并展示图片
function fileUpload(mediaId) {
$.ajax({
url: KY.basePath + "/image/upload.htm",
dataType: 'json',
data: {
"mi": mediaId
},
type: "post",
success: function(result) {
$("#imghead").attr("src", KY.imageServer + result.path);
}
});
}
附:服务端从微信服务器下载图片的代码,在此处,我是将图片从微信服务器下载后调用另一个专门负责上传图片的项目去进行的上传操作,大家也可以在第73行代码获取到流之后下载到本地。
package com.hyde.carelink2.wechat.utils; import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.commons.httpclient.NameValuePair;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper;
import com.hyde.carelink2.wechat.domain.upload.UploadImagResponse;
import com.hyde.carelink2.wechat.service.wechat.WechatServerCenter;
import com.hyde.common.StatusCode;
import com.hyde.common.enums.ImageToken;
import com.hyde.common.enums.ProjectType;
import com.hyde.common.utils.HttpUtil;
import com.hyde.config.enums.ConfigType;
import com.hyde.config.impl.CommonConfig; /**
* @author WangHuijie
*/
public class DownloadImageUtil { private final static Logger LOGGER = LoggerFactory.getLogger(DownloadImageUtil.class); private static ObjectMapper objectMapper = new ObjectMapper(); /**
* 从微信服务器获取媒体文件
*
* @param param
* @param mediaId
* @param request
* @return
*/
public static Map<String, String> getImageFromWechat(String mediaId) { Map<String, String> map = new HashMap<String, String>();
String accessToken = ""; // 接口访问凭证
try {
accessToken = WechatServerCenter.getAccessToken();
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
String filePath = "";
// 拼接请求地址
String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + accessToken + "&media_id=" + mediaId;
try {
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/form-data");
InputStream inputStream = conn.getInputStream(); if (inputStream != null) {
HttpURLConnection conn1 = (HttpURLConnection) url.openConnection();
conn1.setDoInput(true);
conn1.setDoOutput(true);
conn1.setRequestMethod("GET");
conn1.setRequestProperty("Content-Type", "application/form-data");
InputStream inputStream1 = conn1.getInputStream(); if (inputStream1 != null) {
// 根据内容类型获取扩展名
String contentType = conn1.getHeaderField("Content-Type");
String expandName = getFileexpandedName(contentType);
String fileName = mediaId + expandName;
filePath = getUploadServerPath(inputStream1, contentType, fileName);
map.put("path", filePath);
map.put("code", String.valueOf(StatusCode.SUCCESS.getIndex()));
map.put("msg", StatusCode.SUCCESS.getMessage());
} else {
map.put("code", String.valueOf(StatusCode.ERROR.getIndex()));
map.put("msg", StatusCode.ERROR.getMessage());
}
} else {
map.put("code", String.valueOf(StatusCode.ERROR.getIndex()));
map.put("msg", StatusCode.ERROR.getMessage());
}
inputStream.close();
conn.disconnect();
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
return map;
} public static String getUploadServerPath(InputStream inputStream, String contentType, String fileName) { String filePath = null;
byte[] bytes = new byte[0];
try {
bytes = toByteArray(inputStream);
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
String token = "DM5344d93e19c41adb5e0f5531bdd0336";
ProjectType projectType = ProjectType.CARELINK2;
ImageToken type = ImageToken.CARELINK2_USER_PORTRAIT;
UploadImagResponse response = uploadImage(bytes, token, contentType, fileName, projectType, type);
if (response != null) {
filePath = response.getFilePath();
}
return filePath;
} /**
* 执行文件上传到图片服务器
*
* @param bytes
* @param token
* @param contentType
* @param fileName
* @param param
* @return
*/
protected static UploadImagResponse uploadImage(byte[] bytes, String token, String contentType, String fileName, ProjectType projectType, ImageToken type) { try {
ByteArrayBody arrayBody = new ByteArrayBody(bytes, ContentType.create(contentType), fileName);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
NameValuePair projectTypePair = new NameValuePair("p", String.valueOf(projectType.getIndex()));
pairs.add(projectTypePair);
NameValuePair typePair = new NameValuePair("type", String.valueOf(type.getIndex()));
pairs.add(typePair);
String url = CommonConfig.getConfig(ConfigType.UPLOAD_SERVICE_URL, String.class);
String status = HttpUtil.postFile(url, arrayBody, token, pairs);
UploadImagResponse response = objectMapper.readValue(status, UploadImagResponse.class);
return response;
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
return null;
} /**
* 将输入流转为byte数组
* @param input
* @return
* @throws IOException
*/
public static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
} /**
* 根据内容类型判断文件扩展名
* @param contentType 内容类型
* @return
*/
public static String getFileexpandedName(String contentType) { String fileEndWitsh = "";
if ("image/jpeg".equals(contentType)) {
fileEndWitsh = ".jpg";
} else if ("audio/mpeg".equals(contentType)) {
fileEndWitsh = ".mp3";
} else if ("audio/amr".equals(contentType)) {
fileEndWitsh = ".amr";
} else if ("video/mp4".equals(contentType)) {
fileEndWitsh = ".mp4";
} else if ("video/mpeg4".equals(contentType)) {
fileEndWitsh = ".mp4";
}
return fileEndWitsh;
} }
最新文章
- php.ini 中文注释
- 【学】AngularJS日记(1) - 常用工具
- 你真的了解UIView吗?
- 循序渐进Python3(七) -- 2-- 面向对象进阶
- PHP基础12:数组
- XmlPull
- java 处理xml格式数据
- 利用反射得到android存储路径
- LESS语法备忘
- 采购术语PR、PO、RFQ、RFI、SOW、BOM、JIT、VMI、MRO 是什么意思
- 抽出SqlHelper
- 基于Tkinter利用python实现颜色空间转换程序
- 励研(LY) CRC16算法
- flask笔记一
- 快速学会require的使用
- python学习资料链接
- java人民币读法转换
- spring-boot-starter-druid
- EF中防止sql注入
- c++ cin cin.getline() getline()用法