카메라 활성화, 로컬 사진 표시, 사진 업로드 및 다운로드를 위한 WeChat 개발 방법

高洛峰
풀어 주다: 2017-03-09 15:33:23
원래의
1998명이 탐색했습니다.

이 글에서는 위챗 개발에서 카메라 설정, 사진 표시, 사진 업로드 및 다운로드 방법을 소개합니다

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, 
    sizeType: ['compressed'], 
    sourceType: ['album', 'camera'], 
    success: function (res) {
    //var localIds = res.localIds;
      $('.driver-card img').prop('src',res.localIds[0]);
      uploadPhoto.uploadToWeixinServer(res.localIds[0],'car')
   }
});
로그인 후 복사


이때 이런 효과를 볼 수 있는데, 이는 전송이 성공했다는 의미입니다! chooseImage 메서드의 성공적인 콜백에서는 표시해야 하는 img의 src에 선택한 사진을 할당합니다(여기에는 사진이 하나만 있기 때문입니다. 사진이 여러 개인 경우 이 방법으로 루프 할당을 사용하면 됩니다). , 방금 찍은 사진을 바로 표시할 수 있습니다. /앨범에서 선택한 사진

카메라 활성화, 로컬 사진 표시, 사진 업로드 및 다운로드를 위한 WeChat 개발 방법

3. 사진 업로드

위의 chooseImage 성공 콜백에서 uploadToWeixinServer 메소드가 호출되는 것을 볼 수 있으며 매개변수는 로컬 사진의 ID입니다


uploadToWeixinServer: 1
로그인 후 복사


uploadImage 인터페이스를 호출한 후 이미지가 WeChat 서버에 업로드되고 이미지가 반환됩니다. 이때 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
                        
                    }
                }
            });
        },
로그인 후 복사


컨트롤러


@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

WeChat 서버에 있는 이미지를 다운로드하기 위해 WeChat에서 제공하는 임시 자료 인터페이스를 호출합니다. 매개변수는 프런트 엔드에서 제출한 미디어 파일 ID입니다. 그리고 마지막으로 파일을 변환합니다. 입력 스트림 객체


/**
     * 根据文件id下载文件 
     * @param accessToken
     * @param mediaId 
     * @return 文件流对象     */
    public InputStream getInputStream(String accessToken, String mediaId) {  
        InputStream is = null;  
        String url = "http://www.php.cn/"+ 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");
                }  
            }  
        }  
    }
로그인 후 복사


위 내용은 카메라 활성화, 로컬 사진 표시, 사진 업로드 및 다운로드를 위한 WeChat 개발 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!