jssdk 上传图片 java_微信JS-SDK实现上传图片功能

该代码段展示了如何从微信服务器获取媒体文件并上传到图片服务器的过程。首先通过调用微信接口获取访问令牌,然后利用访问令牌下载指定的媒体文件。下载完成后,根据文件内容类型获取扩展名,并将文件上传到图片服务器,返回文件的存储路径。整个过程涉及网络请求、文件处理和JSON序列化操作。
摘要由CSDN通过智能技术生成

1 packagecom.hyde.carelink2.wechat.utils;2

3 importjava.io.ByteArrayOutputStream;4 importjava.io.IOException;5 importjava.io.InputStream;6 importjava.net.HttpURLConnection;7 importjava.net.URL;8 importjava.util.ArrayList;9 importjava.util.HashMap;10 importjava.util.List;11 importjava.util.Map;12

13 importorg.apache.commons.httpclient.NameValuePair;14 importorg.apache.http.entity.ContentType;15 importorg.apache.http.entity.mime.content.ByteArrayBody;16 importorg.slf4j.Logger;17 importorg.slf4j.LoggerFactory;18

19 importcom.fasterxml.jackson.databind.ObjectMapper;20 importcom.hyde.carelink2.wechat.domain.upload.UploadImagResponse;21 importcom.hyde.carelink2.wechat.service.wechat.WechatServerCenter;22 importcom.hyde.common.StatusCode;23 importcom.hyde.common.enums.ImageToken;24 importcom.hyde.common.enums.ProjectType;25 importcom.hyde.common.utils.HttpUtil;26 importcom.hyde.config.enums.ConfigType;27 importcom.hyde.config.impl.CommonConfig;28

29 /**

30 *@authorWangHuijie31 */

32 public classDownloadImageUtil {33

34 private final static Logger LOGGER = LoggerFactory.getLogger(DownloadImageUtil.class);35

36 private static ObjectMapper objectMapper = newObjectMapper();37

38 /**

39 * 从微信服务器获取媒体文件40 *41 *@paramparam42 *@parammediaId43 *@paramrequest44 *@return

45 */

46 public static MapgetImageFromWechat(String mediaId) {47

48 Map map = new HashMap();49 String accessToken = ""; //接口访问凭证

50 try{51 accessToken =WechatServerCenter.getAccessToken();52 } catch(Exception e) {53 LOGGER.error(e.getMessage(), e);54 }55 String filePath = "";56 //拼接请求地址

57 String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + accessToken + "&media_id=" +mediaId;58 try{59 URL url = newURL(requestUrl);60 HttpURLConnection conn =(HttpURLConnection) url.openConnection();61 conn.setDoInput(true);62 conn.setDoOutput(true);63 conn.setRequestMethod("GET");64 conn.setRequestProperty("Content-Type", "application/form-data");65 InputStream inputStream =conn.getInputStream();66

67 if (inputStream != null) {68 HttpURLConnection conn1 =(HttpURLConnection) url.openConnection();69 conn1.setDoInput(true);70 conn1.setDoOutput(true);71 conn1.setRequestMethod("GET");72 conn1.setRequestProperty("Content-Type", "application/form-data");73 InputStream inputStream1 =conn1.getInputStream();74

75 if (inputStream1 != null) {76 //根据内容类型获取扩展名

77 String contentType = conn1.getHeaderField("Content-Type");78 String expandName =getFileexpandedName(contentType);79 String fileName = mediaId +expandName;80 filePath =getUploadServerPath(inputStream1, contentType, fileName);81 map.put("path", filePath);82 map.put("code", String.valueOf(StatusCode.SUCCESS.getIndex()));83 map.put("msg", StatusCode.SUCCESS.getMessage());84 } else{85 map.put("code", String.valueOf(StatusCode.ERROR.getIndex()));86 map.put("msg", StatusCode.ERROR.getMessage());87 }88 } else{89 map.put("code", String.valueOf(StatusCode.ERROR.getIndex()));90 map.put("msg", StatusCode.ERROR.getMessage());91 }92 inputStream.close();93 conn.disconnect();94 } catch(Exception e) {95 LOGGER.error(e.getMessage(), e);96 }97 returnmap;98 }99

100 public staticString getUploadServerPath(InputStream inputStream, String contentType, String fileName) {101

102 String filePath = null;103 byte[] bytes = new byte[0];104 try{105 bytes =toByteArray(inputStream);106 } catch(IOException e) {107 LOGGER.error(e.getMessage(), e);108 }109 String token = "DM5344d93e19c41adb5e0f5531bdd0336";110 ProjectType projectType =ProjectType.CARELINK2;111 ImageToken type =ImageToken.CARELINK2_USER_PORTRAIT;112 UploadImagResponse response =uploadImage(bytes, token, contentType, fileName, projectType, type);113 if (response != null) {114 filePath =response.getFilePath();115 }116 returnfilePath;117 }118

119 /**

120 * 执行文件上传到图片服务器121 *122 *@parambytes123 *@paramtoken124 *@paramcontentType125 *@paramfileName126 *@paramparam127 *@return

128 */

129 protected static UploadImagResponse uploadImage(byte[] bytes, String token, String contentType, String fileName, ProjectType projectType, ImageToken type) {130

131 try{132 ByteArrayBody arrayBody = newByteArrayBody(bytes, ContentType.create(contentType), fileName);133 List pairs = new ArrayList();134 NameValuePair projectTypePair = new NameValuePair("p", String.valueOf(projectType.getIndex()));135 pairs.add(projectTypePair);136 NameValuePair typePair = new NameValuePair("type", String.valueOf(type.getIndex()));137 pairs.add(typePair);138 String url = CommonConfig.getConfig(ConfigType.UPLOAD_SERVICE_URL, String.class);139 String status =HttpUtil.postFile(url, arrayBody, token, pairs);140 UploadImagResponse response = objectMapper.readValue(status, UploadImagResponse.class);141 returnresponse;142 } catch(Exception e) {143 LOGGER.error(e.getMessage(), e);144 }145 return null;146 }147

148 /**

149 * 将输入流转为byte数组150 *@paraminput151 *@return

152 *@throwsIOException153 */

154 public static byte[] toByteArray(InputStream input) throwsIOException {155 ByteArrayOutputStream output = newByteArrayOutputStream();156 byte[] buffer = new byte[4096];157 int n = 0;158 while (-1 != (n =input.read(buffer))) {159 output.write(buffer, 0, n);160 }161 returnoutput.toByteArray();162 }163

164 /**

165 * 根据内容类型判断文件扩展名166 *@paramcontentType 内容类型167 *@return

168 */

169 public staticString getFileexpandedName(String contentType) {170

171 String fileEndWitsh = "";172 if ("image/jpeg".equals(contentType)) {173 fileEndWitsh = ".jpg";174 } else if ("audio/mpeg".equals(contentType)) {175 fileEndWitsh = ".mp3";176 } else if ("audio/amr".equals(contentType)) {177 fileEndWitsh = ".amr";178 } else if ("video/mp4".equals(contentType)) {179 fileEndWitsh = ".mp4";180 } else if ("video/mpeg4".equals(contentType)) {181 fileEndWitsh = ".mp4";182 }183 returnfileEndWitsh;184 }185

186 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值