在应用的个人中心,总希望用户可以通过点击头像打开摄像头进行图片上传,如何实现呢?我大致分了几步:
1、通过wx.chooseImage 调用相机打开图片 ,然后返回选定照片的本地ID列表,localId能够作为img标签的src属性显示图片。
uploadImage(){
let that=this;
wx.chooseImage({
count: 1, // 默认9
sizeType: ['original', 'compressed'], // 能够指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 能够指定来源是相冊还是相机,默认二者都有
success: function (res) {
var localIds = res.localIds; // 返回选定照片的本地ID列表,localId能够作为img标签的src属性显示图片
that.uploadImg(localIds[0]);
}
});
}
2、通过wx.uploadImage上传图片到微信服务器上,并返回serverId 。重点:此处通过Promise返回resolve,是为了防止请求异步问题(实际情况就是这样)
uploadImg(e){
let that=this;
that.picUrl="";
this.nativeService.uploadImage(e).then(serverId => {
let params = new HttpParams()
.set("mediaId", serverId)
.set('loginFrom', 'app');
let url = GlobalVariable.BASE_URL + 'wx.do?method=downloadMedia';
this.appService.GET(url, params, (res, err) => {
if (res) {
that.picUrl=GlobalVariable.BASE_URL+that.userPicture;
this.appService.alert("图片上传成功!");
}
if (err) {
console.log(err)
}
});
});
}
补上nativeService.ts文件
/**
* 上传照片
*/
uploadImage(localId:string): Promise<string> {
return new Promise((resolve) => {
wx.uploadImage({
localId: localId, // 需要上传的图片的本地ID,由chooseImage接口获得
isShowProgressTips: 1, // 默认为1,显示进度提示
success (res) {
let serverId = res.serverId;
console.log("serverId="+serverId)
resolve(serverId);
}
});
});
}
3、调用本地后台上传方法,将mediaId传递到后台处理
//获取媒体文件
@FieldMeta(description="获取媒体文件",isPermissionNeeded=false)
@RequestMapping(params="method=downloadMedia")
public void downloadMedia(HttpServletRequest request, HttpServletResponse response,String mediaId) throws Exception {
System.out.println(mediaId);
if(StringUtils.isNotBlank(mediaId)) {
AccessToken at=TokenThread.accesstoken;
String token=at.getToken();
String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
requestUrl = requestUrl.replace("ACCESS_TOKEN", token).replace(
"MEDIA_ID", mediaId);
HttpURLConnection conn = null;
try {
URL url = new URL(requestUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
BufferedInputStream bis = new BufferedInputStream(
conn.getInputStream());
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = bis.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] filebyte = swapStream.toByteArray();
boolean hasCreate=this.uploadImageToServer(request,filebyte);
Success success = new Success();
if(hasCreate){
success.setMsg("Y");
}else{
success.setMsg("N");
}
success.setSuccess(true);
CommonHelper.responseToFront(response, success);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(conn != null){
conn.disconnect();
}
}
}else{
Success success = new Success();
success.setSuccess(true);
success.setMsg("N");
CommonHelper.responseToFront(response, success);
}
}
public boolean uploadImageToServer(HttpServletRequest request,byte[] bytes){
//上传图片到服务器
String userId = (String)request.getSession().getAttribute("userId");
String servletPath = request.getSession().getServletContext().getRealPath("/attachment/userPicture");
File f = new File(servletPath);
if(!f.exists()) {
f.mkdirs();
}
String filePath = servletPath + File.separator + userId +".jpg";
InputStream in = new ByteArrayInputStream(bytes);
BufferedImage image;
try {
image = ImageIO.read(in);
in.close();//必须关闭 不然临时文件 会被占用而导致删除不了
//3.按照指定尺寸缩小
Thumbnails.of(image).size(200, 200).keepAspectRatio(false).toFile(new File(filePath));
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
到此,头像将可以上传成功啦~记得应用的域名配置别搞错了