在應(yīng)用的個人中心到踏,總希望用戶可以通過點擊頭像打開攝像頭進行圖片上傳,如何實現(xiàn)呢我抠?我大致分了幾步:
1乏沸、通過wx.chooseImage 調(diào)用相機打開圖片 ,然后返回選定照片的本地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上傳圖片到微信服務(wù)器上襟铭,并返回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哩都、調(diào)用本地后臺上傳方法魁兼,將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){
//上傳圖片到服務(wù)器
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();//必須關(guān)閉 不然臨時文件 會被占用而導(dǎo)致刪除不了
//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;
}
}
到此,頭像將可以上傳成功啦~記得應(yīng)用的域名配置別搞錯了