zoukankan      html  css  js  c++  java
  • 微信上传图片到七牛

    HTML代码:

    <body>
    <div class="screen">
    <div class="layout_content_full background-color_dividing">
    <div class="background-color_white preview_title_box">
    <h5>请选择一个评价</h5>
    <div class="air_tab_list fif_top">
    <button id="tab1" class="evaluation_select air_tab_item evaluation_selected" for="0" >强烈推荐</button>
    <button class="evaluation_select air_tab_item" for="1">一般般</button>
    <button class="evaluation_select air_tab_item" for="2">可以尝试</button>
    <button class="evaluation_select air_tab_item" for="3">真的很烂</button>

    </div>
    </div>
    <div class="dividing_line3"></div>
    <div class="mui-input-row address_row message_h row_then-last">
    <textarea id='content_text' class="widget_title input_change login_word" placeholder="请输入您想要说的" onfocus="this.placeholder=''"/></textarea>
    </div>
    <div class="background-color_white btn_group">
    <button type="button" id="add_pic" class="pic_btn complain_square" style="border: rgba(128, 128, 128, 0.36) solid 1px;">
    <h1 class="color_content">+</h1>
    <h5 class="color_content">添加照片</h5>
    </button>
    <!-- <input id="upload_image1" type="file" name="image" accept="image/*" style="display: none;" /> -->
    </div>
    <button class="button_sure orange_background color_white" id="btnAdd">立即发布</button>
    </div>
    </div>
    <div id="container" hidden="hidden">
    <a id="forumFile" href="#">上传文件</a> <span id="forumFile_msg"
    style="font-size: 11px; color: red"></span>
    <div id="upload_sucess" style="display: none;">上传成功</div>
    </div>
    <script type="text/javascript" src="lib/jquery-2.2.4.min.js"></script>
    <script type="text/javascript" src="lib/mui.min.js"></script>
    <script type="text/javascript" src="js/constant.js"></script>
    <script type="text/javascript" src="js/sys.js"></script>
    <script type="text/javascript" src="js/sys2.js"></script>
    <script type="text/javascript" src="lib/jquery.cookie.js"></script>
    <script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
    <script type="text/javascript" src="js/imgEditor.js"></script>
    <script>
    var id="",b_id="";

    $(function() {
    //tabchange
    $(".air_tab_list>button").click(function(){
    $(this).siblings().removeClass('evaluation_selected').end().addClass('evaluation_selected');
    });
    //上传图片
    init();
    var id=getUrlParam("id");
    if(id){
    /* showData(); */
    }
    var b_id=getUrlParam("b_id");
    if(b_id)
    {
    $(".button_sure").click(function(){
    if(!(checkupload())){
    tipDialog.show(tip_fail,'温馨提示',"图片还未上传完成");
    return;
    }
    //if(!b_id){
    //tipDialog.show(tip_fail,'温馨提示',"商户id不能为空");
    //return;
    //}
    //postData(b_id);
    })
    }
    });

    </script>

    imgEditor.js代码:

    function addImgHtml(src) {
    var insertHtml = '<button class="pic_btn"><img src="' + src + '" class="complain_square"/><span class="background-color_content color_white close">×</span></button>'
    $('.background-color_white.btn_group').append(insertHtml);
    }

    $.ready(
    $(".background-color_white.btn_group").on('tap', '.close',function () {
    $(this).parent().remove();
    removeimgLen++;
    })
    )
    function initWx() {
    $.ajax({
    type: "POST",
    url: KL_BASE_URL + "/apigateway_wx/weixin/gch/pay/weixin/v1/h5Config.do",
    data: {},
    dataType: "json",
    success: function (data) {
    if (data["code"] == 200) {
    tstmp = data["data"]["response"]["timestamp"];
    nonceStr = data["data"]["response"]["noncestr"];
    wx.config({
    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
    appId: data["data"]["response"]["appId"], // 必填,公众号的唯一标识
    timestamp: data["data"]["response"]["timestamp"], // 必填,生成签名的时间戳
    nonceStr: data["data"]["response"]["noncestr"], // 必填,生成签名的随机串
    signature: data["data"]["response"]["paySign"], // 必填,签名,见附录1
    jsApiList: ['chooseImage', 'uploadImage','chooseWXPay'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
    });
    } else {
    tipDialog.show(tip_fail, '温馨提示', data["message"]);
    }
    },
    error: function () {
    tipDialog.show(tip_fail, '温馨提示', "微信图片接口初始化失败!", function () {
    reloadPage();
    });
    }
    });
    }

    var currentImgCount=0,localIdsLenth=0,chooseimgLen=0,removeimgLen=0;

    function fetchToQiniu(serviceId) {
    if ($("img[class='complain_square']").length >= 9) {
    tipDialog.show(tip_fail, '温馨提示', "最多只能添加9张图片!");
    return;
    }

    $.ajax({
    type: "POST",
    url: KL_BASE_URL + "/apigateway_wx/weixin/gch/pay/weixin/v1/fetchToQiniu.do",
    data: {
    serviceId: serviceId
    },
    dataType: "json",
    success: function (data) {
    if (data["code"] == 200) {
    var key = data["data"]["response"];
    addImgHtml(FILE_BASE_URL_PREX + key);
    currentImgCount++;
    } else {
    tipDialog.show(tip_fail, '温馨提示', data["message"]);
    }
    },
    error: function () {
    tipDialog.show(tip_fail, '温馨提示', "上传失败,请重试!");
    }
    });


    }
    function init() {
    initWx();
    wx.ready(function () {
    $("#add_pic").click(function () {
    //限制9张
    var imglength=$("img[class='complain_square']").length;
    if (imglength>= 9||9-imglength<=0) {
    tipDialog.show(tip_fail, '温馨提示', "最多只能添加9张图片!");
    return;
    }
    wx.chooseImage({
    count: 9-imglength, // 默认9
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
    success: function (res) {
    var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
    localIdsLenth=localIds.length;
    syncUpload(localIds);
    }
    });

    var syncUpload = function (localIds) {
    var localId = localIds.pop();
    wx.uploadImage({
    localId: localId,
    isShowProgressTips: 0,// 默认为1,显示进度提示
    success: function (res) {
    var serverId = res.serverId; // 返回图片的服务器端ID
    //其他对serverId做处理的代码
    fetchToQiniu(serverId);
    if (localIds.length > 0) {
    syncUpload(localIds);
    }

    }
    });
    }
    });


    });

    }

    function getContentJson() {
    var content_text = $("#content_text").val();
    if(content_text.length == 0){
    tipDialog.show(tip_fail,'温馨提示',"详情不能为空!");
    return;
    }
    if(content_text.length >50){
    content_text=content_text.substring(0,50);
    $("#content_text").val(content_text);
    tipDialog.show(tip_fail,'温馨提示',"详情内容超过限制的50个字符,</br>请重新填写确认");
    return;
    }
    var arr = new Array();
    arr.push({ "type": "text", "content": content_text });
    $(".pic_btn img").each(function () {
    arr.push({ "type": "image", "content": $(this).attr("src") });
    });
    return arr;
    }

    function checkupload(){
    chooseimgLen=$("img[class='complain_square']").length;
    if(currentImgCount!=(chooseimgLen+removeimgLen)||currentImgCount<localIdsLenth){
    return false;
    }
    else{
    return true;
    }
    }

    java代码:

    @RequestMapping("v1/fetchToQiniu.do")
    @ResponseBody
    public void fetchToQiniu(HttpServletRequest request, HttpServletResponse response) {
    try {
    String serviceId = request.getParameter("serviceId");
    String url = weixinService.fetchToQiniu(serviceId, business_id);
    if(StringUtils.isBlank(url)){
    Util.returnJsonResponse(response, 202, "fetch失败", null);
    return;
    }
    Util.returnJsonResponse(response, 200, "fetch成功", url);
    } catch (Exception e) {
    logger.error("微信获取fetch异常", e);
    RsExceptionHandler.doHandler(response, e);
    }
    }

    weixinService.fetchToQiniu代码段:

    /**
    * 抓取
    *
    * @return
    */

    public String fetchToQiniu(String serviceId, Integer business_id) throws Exception {
    if(StringUtils.isBlank(serviceId)){
    return null;
    }
    Map<String, Object> param = new HashMap<String, Object>();
    param.put("business_id", business_id);
    HttpResult tokenResult = WeixinPayRsService.getToken(param, "v1");
    if (200 != tokenResult.getCode()) {
    return null;
    }
    String token = JsonToObject.httpResultToString(tokenResult);
    String imgHttpUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="
    + token + "&media_id=" + serviceId;
    String filePath = QiniuFileService.business_qiniu_path_;
    String fileName = UUID.randomUUID().toString();
    //boolean result = QiniuFileService.fetch(imgHttpUrl, filePath, filePath + fileName);
    String path = GetWebConfig.getValue("file.temppath");
    String down_ret = WeixinLibImageUtils.downloadImageByHttpUrl(imgHttpUrl, path + fileName);
    if (down_ret != null && !down_ret.equals("NO_IMG")) {
    logger.error("微信fetch,下载成功");
    String fullName = path + fileName;
    boolean ret = QiniuFileService.upload(fullName, fileName);
    if (ret == true) {
    return filePath + fileName;
    }
    }else{
    //失败了,刷新token
    logger.error("微信fetch,下载失败,刷新token,重试");
    param.put("need_refresh", true);
    tokenResult = WeixinPayRsService.getToken(param, "v1");
    if (200 != tokenResult.getCode()) {
    return null;
    }
    token = JsonToObject.httpResultToString(tokenResult);
    imgHttpUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="
    + token + "&media_id=" + serviceId;
    down_ret = WeixinLibImageUtils.downloadImageByHttpUrl(imgHttpUrl, path + fileName);
    if (down_ret != null && !down_ret.equals("NO_IMG")) {
    String fullName = path + fileName;
    boolean ret = QiniuFileService.upload(fullName, fileName);
    if (ret == true) {
    return filePath + fileName;
    }
    }
    }

    logger.error("微信fetch重试后异常...");
    return null;
    }

    QiniuFileService .java代码:

    package com.apigateway.service.gch;

    import com.apigateway.qiniu.manager.QiniuHandle;
    import com.apigateway.qiniu.manager.QiniuManager;
    import org.apache.log4j.Logger;

    public class QiniuFileService {
    private static final Logger logger = Logger.getLogger(QiniuFileService.class);

    public static final String business_qiniu_path = "guchenghu";
    public static final String business_qiniu_path_ = "guchenghu/";


    private static QiniuHandle screen_handle = QiniuManager.getQiniuHandle("guchenghu", false);


    public static boolean delete(String key) {
    if (key == null || key.trim().equals("")) {
    return true;
    }
    return screen_handle.delete(key);
    }


    public static boolean upload(String filePath, String fileName) {
    return screen_handle.upload(filePath, fileName);
    }

    public static String getDownloadUrl(String fileName) {
    return screen_handle.getDownloadUrl(fileName, null);
    }

    public static String getDownloadUrl_(String fileName) {
    return screen_handle.getDownloadUrl(fileName, null);
    }

    public static String getUpToken() {
    return screen_handle.getUpToken();
    }

    public static String url() {
    return screen_handle.getUrl();
    }

    public static boolean fetch(String url, String filePath, String fileName) {
    return screen_handle.fetch(url, filePath, fileName);
    }

    /*
    public static Auth auth = Auth.create("csjvy15GQIJLY-efz0wtaKKUJZYnz-Opwnid665n", "abbqkJ55nvCtQrx9PRJnt3pq1NDLxzGVgNDMJrMV");

    public static String url = "http://7xrqc0.com1.z0.glb.clouddn.com/";

    public static void main(String[] args) throws Exception {

    //download();

    //delete("002293d0-b021-4406-a45c-6ebee23b38e5.cebx");

    upload();

    //delete("3f010c50-6a6e-4935-b1e7-9e3218c7d775.m4v");

    System.out.println(getDownloadUrl("1fb8ed17-00e0-4abc-94c6-51d7a5be1d03.jpg"));
    }

    public static void upload() {
    UploadManager uploadManager = new UploadManager();
    try {
    File file = new File("E:\xueshufeng\workspace_xue\write me\test.doc");
    Response res = uploadManager.put(file, "a/b/我.doc", getUpToken());
    MyRet ret = res.jsonToObject(MyRet.class);
    logger.info(res.toString());
    logger.info(res.bodyString());
    } catch (QiniuException e) {
    Response r = e.response;
    // 请求失败时简单状态信息
    logger.error(r.toString());
    try {
    // 响应的文本信息
    logger.error(r.bodyString());
    } catch (QiniuException e1) {
    //ignore
    }
    }
    }

    public static boolean delete(String key){
    BucketManager bucketManager = new BucketManager(auth);
    try {
    bucketManager.delete("screen", key);
    } catch (QiniuException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    return false;
    }


    return true;
    }
    public static boolean upload(String filePath, String fileName){
    UploadManager uploadManager = new UploadManager();
    try {
    File file = new File(filePath);
    Response res = uploadManager.put(file,fileName, getUpToken());
    MyRet ret = res.jsonToObject(MyRet.class);
    logger.info(res.toString());
    logger.info(res.bodyString());
    return true;
    } catch (QiniuException e) {
    Response r = e.response;
    // 请求失败时简单状态信息
    logger.error(r.toString());
    try {
    // 响应的文本信息
    logger.error(r.bodyString());
    } catch (QiniuException e1) {
    //ignore
    }
    }
    return false;
    }

    public class MyRet {
    public long fsize;
    public String key;
    public String hash;
    public int width;
    public int height;
    }

    public static String getUpToken(){
    return auth.uploadToken("screen", null, 3600, new StringMap()
    .putNotEmpty("returnBody", "{"key": $(key), "hash": $(etag), "width": $(imageInfo.width), "height": $(imageInfo.height)}"));
    }

    public static String getUpToken1(){
    return auth.uploadToken("screen", null, 3600, new StringMap()
    .putNotEmpty("returnBody", "{"key": $(key), "hash": $(etag)}"));
    }

    public static void download() {
    String url2 = "http://7xrqc0.com1.z0.glb.clouddn.com/%E6%88%91.doc";
    String urlSigned = auth.privateDownloadUrl(url2,60);
    System.out.println(urlSigned);
    }

    public static String getDownloadUrl(String fileName){
    String url2 = "http://7xrqc0.com1.z0.glb.clouddn.com/"+fileName;
    String urlSigned = auth.privateDownloadUrl(url2);
    return urlSigned;
    }

    */
    }

    WeixinLibImageUtils.java代码:

    package com.apigateway.service.gch;

    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;

    import org.apache.commons.io.IOUtils;
    import org.apache.http.Header;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.ResponseHandler;

    import com.apigateway.util.HttpClientUtils;
    import com.util.StringUtil;

    /**
    * 项目图片工具类
    *
    * @author
    * @date 2016年3月15日 下午4:44:03
    * @version 1.0
    */
    public class WeixinLibImageUtils {


    /**
    * 下载HTTP图片到本地
    * @param imgHttpUrl - 要下载的图片HTTP全路径
    * @param realImgSavePath - 图片保存的相对路径(其相对于 #GlobalURLConstants.GLOBAL_IMAGE_SERVER_ROOT)
    * @return fullImgFilePath - 返回图片保存的物理全路径 (返回null则表示下载失败)
    */
    public static String downloadImageByHttpUrl(String imgHttpUrl, String realImgSavePath) {
    if(!StringUtil.isEmpty(imgHttpUrl) && !StringUtil.isEmpty(realImgSavePath)){

    String fullImgFilePath = realImgSavePath;
    return HttpClientUtils.doGet(imgHttpUrl, new ImageResponseHandler(fullImgFilePath));
    }
    return null;
    }

    public static class ImageResponseHandler implements ResponseHandler<String> {

    private final String fullImgFilePath;

    public ImageResponseHandler(String fullImgFilePath) {
    super();
    this.fullImgFilePath = fullImgFilePath;
    }

    @Override
    public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
    HttpEntity httpEntity = response.getEntity();
    Header[] headers = response.getHeaders("Content-Type");
    if(headers != null && headers.length > 0){
    for(int i = 0; i< headers.length; i++){
    if(headers[i].getValue().contains("application/json")){
    return "NO_IMG";
    }
    }
    }


    if(httpEntity != null){
    InputStream in = null;
    OutputStream out = null;
    try {

    File tempFile = new File(fullImgFilePath);
    if (!tempFile.exists()) {
    tempFile.createNewFile();
    }

    in = httpEntity.getContent();
    out = new FileOutputStream(fullImgFilePath);
    IOUtils.copy(in, out);
    } finally {
    IOUtils.closeQuietly(in);
    IOUtils.closeQuietly(out);
    }
    return fullImgFilePath;
    }
    return null;
    }
    }

    public static void main(String[] args) {

    String ret = downloadImageByHttpUrl("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=1211212&media_id=1212","d:/aa.jpg");
    System.out.println(ret);
    }

    }

  • 相关阅读:
    如何通过wlst部署应用程序到weblogic12c上
    Oracle数据库账户口令复杂度-等保测评之身份鉴别
    等保测评中与oracle有关的工作
    如何做好项目管理工作
    weblogic 安全漏洞 CVE-2017-5638
    中间件中文技术文档2018年3月-5月更新内容
    Admin Console 反应慢的相关bug
    HotSpot jdk 资料汇总
    weblogic patch log显示
    Where Can I Download Full Installers for WebLogic Server
  • 原文地址:https://www.cnblogs.com/ft-Pavilion/p/6873182.html
Copyright © 2011-2022 走看看