国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

微信開發之調起攝像頭、本地展示圖片、上傳下載圖片實例

2019-11-19 18:36:35
字體:
來源:轉載
供稿:網友

之前那篇微信JS-SDK授權的文章實現了分享接口,那么這里總結一下如何在微信里面通過js調起原生攝像頭,以及上傳下載圖片。

1.配置

頁面引入通過jssdk授權后,傳入wx對象,首先配置需要的接口

wx.config({  /* debug: true, */  appId: appid,   timestamp: timestamp,   nonceStr: nonceStr,   signature: signature,  jsApiList: [     'chooseImage',//拍照或從手機相冊中選圖接口     'previewImage',//預覽圖片接口     'uploadImage',//上傳圖片接口     'downloadImage'//下載圖片接口   ] });

2.調起拍照/相冊

將下面的方法放在需要點擊事件的回調函數里面

wx.chooseImage({  count: 1, //張數, 默認9  sizeType: ['compressed'], //建議壓縮圖  sourceType: ['album', 'camera'], // 來源是相冊、相機  success: function (res) {    //var localIds = res.localIds; // 返回選定照片的本地ID列表,localId可以作為img標簽的src屬性顯示圖片    $('.driver-card img').prop('src',res.localIds[0]);    uploadPhoto.uploadToWeixinServer(res.localIds[0],'car')  }});

這時我們可以看到這樣的效果,代表調起成功了!chooseImage方法的成功回調里,我將選中的照片賦值給需要顯示的img的src(因為我這里只有一張照片,如果有多張用循環賦值即可),這樣一來,就可以直接顯示剛剛拍照/相冊里選中的照片了

 

3.上傳照片

在上面chooseImage的success回調里面,可以看到我調用了uploadToWeixinServer方法,參數為本地照片的Id

uploadToWeixinServer: function(localId,type){      wx.uploadImage({        localId: localId,        isShowProgressTips: 1, // 默認為1,顯示進度提示        success: function (res) {            //res.serverId 返回圖片的微信服務器端ID          uploadPhoto.uploadToOwnerServer(res.serverId,type);//異步上傳到我們自己的服務器        }      });    },

調用uploadImage接口后,將圖片上傳到了微信服務器,返回圖片的ID,這個時候需要用ajax異步上傳到自己的服務器里,調用微信提供的“獲取臨時素材”接口。當然也不一定是選擇完照片就立即上傳,還得根據實際業務需求出發,也有是靜默上傳(沒有進度提示),也有是在最終提交表單時一起上傳

js:

uploadToOwnerServer: function(serverId,type){      $.ajax({        data: {serverId:serverId,type:type},        type : "POST",        url : WX_ROOT + "wechat/uploadPhoto",        success : function(json) {          if (json) {            var data = JSON.parse(json.data);            if ('car' == type)               uploadPhoto.options.carImage = data.path + data.name            else              uploadPhoto.options.idCardImage = data.path + data.name                      }        }      });    },

Controller

@RequestMapping(value = "/uploadPhoto", method = RequestMethod.POST)  public @ResponseBody HttpResult uploadPhoto(@RequestParam String serverId,@RequestParam String type) throws Exception{    LOGGER.info("RestFul of uploadPhoto parameters serverId:{},type:{}",serverId,type);        try {      /** 將圖片保存到本地服務器 **/      String photoName = type + new Date().getTime() + UUID.randomUUID().toString();            //文件路徑不存在則創建      File saveFile = new File(PIC_PATH + type);      if (!saveFile.mkdir()) saveFile.mkdir();            wechatService.saveImageToDisk(serverId, photoName, PIC_PATH + type + "/");      LOGGER.info("Download the picture from weixin server pathL:{}",PIC_PATH + type + "/");      JSONObject data = new JSONObject();      data.put("name", type + "/" + photoName+".jpg");      data.put("path", PIC_SERVER + "/");            HttpResult rs = new HttpResult();      rs.setCode(200);      rs.setData(data.toJSONString());      LOGGER.info("Download the picture from weixin server is successful!serverId:{},photoName:{}",serverId,photoName);      LOGGER.info("HttpResult data:{}",rs.getData());      return rs;    } catch (Exception e) {      LOGGER.error("Download the picture from weixin server is error",serverId);      return null;    }

這里我使用了一個UUID生成主鍵規則,通過類型+時間戳+唯一字符串定義圖片名稱。如果上傳成功,同時又將自己服務器的圖片地址返回給前端。

getInputStream

調用微信提供的獲取臨時素材接口下載還在微信服務器上的圖片,參數為前端提交上來的媒體文件ID,最終將文件轉化為輸入流對象

/**   * 根據文件id下載文件    * @param accessToken   * @param mediaId    * @return 文件流對象   */  public InputStream getInputStream(String accessToken, String mediaId) {     InputStream is = null;     String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="+ accessToken + "&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) {       LOGGER.error("Failed to convert inputStream from weixin server,accessToken:{},mediaId:{}",accessToken,mediaId);    }     return is;    }

service

通過循環解析流對象,將文件寫入自己的服務器

public void saveImageToDisk(String mediaId, String picName, String picPath) throws Exception {     String accessToken = getBaseAccessToken();    InputStream inputStream = getInputStream(accessToken, mediaId);         // 循環取出流中的數據    byte[] data = new byte[1024];     int len = 0;     FileOutputStream fileOutputStream = null;     try {       fileOutputStream = new FileOutputStream(picPath+picName+".jpg");       while ((len = inputStream.read(data)) != -1) {         fileOutputStream.write(data, 0, len);       }       LOGGER.info("Write the fileInputStream is successful");    } catch (IOException e) {       LOGGER.error("Write the fileInputStream is error");    } finally {       if (inputStream != null) {         try {           inputStream.close();         } catch (IOException e) {           LOGGER.error("Close the fileInputStream is error");        }       }       if (fileOutputStream != null) {         try {           fileOutputStream.close();         } catch (IOException e) {           LOGGER.error("Close the fileOutputStream is error");        }       }     }   }

 4.總結

那么到這里,簡單的拍照,展示圖片,上傳下載的功能都已經完成,其實代碼就是最好的注釋!微信開放的jssdk提供了很多友好而有趣的功能,接下來還需要繼續實踐研究....

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 黔西县| 迁安市| 新晃| 富阳市| 郴州市| 文化| 达孜县| 丹巴县| 万年县| 东安县| 奈曼旗| 锡林郭勒盟| 额敏县| 贵阳市| 苏尼特右旗| 睢宁县| 汾阳市| 眉山市| 鄂尔多斯市| 息烽县| 遵化市| 阿拉善左旗| 元阳县| 海安县| 孟津县| 都江堰市| 宁明县| 巴东县| 项城市| 鄂州市| 安义县| 昌黎县| 嘉禾县| 斗六市| 文登市| 日喀则市| 邹平县| 抚远县| 安龙县| 海原县| 甘泉县|