多张图片,一张一张上传(处理结果那有点蠢)

    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private static OkHttpClient client = new OkHttpClient();
    private static UpLoadListener upLoadListener;
    private static List resultList = null;//图片上传后的结果集
    private static List picList = null;//需要上传的图片集合

向外暴露结果接口:

   public interface UpLoadListener {
        abstract void upLoadResult(List list);
        abstract void upLoadError(String message);
    }

初始化:

  upLoadListener = (UpLoadListener) context;

上传图片

     public void uploadImg(List list, final String xtype) {
        if (null == resultList)
            resultList = new ArrayList<>();
        else resultList.clear();
        picList = list;
        final ExecutorService exec = Executors.newFixedThreadPool(list.size());
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        singleThreadExecutor.execute(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < picList.size(); i++) {
                    try {
                        final String localPath = picList.get(i).getLocalPath();
                        Runnable task = new Runnable() {
                            @Override
                            public void run() {
                                postPicData(xtype, localPath);
                            }
                        };
                        exec.submit(task);

                    } catch (Exception e) {

                    }
                }
                exec.shutdown();
             

            }
        });

    }
      public void postPicData(String xtype, String path) {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        File f = new File(path);
        Bitmap bitmap = BitmapTools.getimage(path);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        byte[] data = bos.toByteArray();
        if (f != null)
            builder.addFormDataPart("Filedata", f.getName(), RequestBody.create(MEDIA_TYPE_PNG, data));
        Map map = Tools
                .getToken("ChuangXinQuChengNongJi360YuRunSiJi");
        String timestamp = map.get("timestamp").toString();
        String sha1 = map.get("token").toString();
        builder.addFormDataPart("xtype", xtype);
        builder.addFormDataPart("timestamp", timestamp);
        builder.addFormDataPart("token", sha1);
        MultipartBody requestBody = builder.build();
        //构建请求
        Request request = new Request.Builder()
                .method("GET", null)
                .url(BaseUrl.photoUpLoadUrl)//地址
                .post(requestBody)//添加请求体
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {//上传图片出错
                error(e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {//上传图片操作成功
                String json = response.body().string();
                PicUpResult result = FastJsonTools.getBean(json, PicUpResult.class);
                if (null != result) {
                    int status = result.getStatus();
                    if (status == 111111) {//成功
                        String resultUrl = result.getUrl();
                        String resultThumb = result.getThumb();
                        success(resultUrl,resultThumb);
                    } else {
                        final String message = result.getMessage();
                         error(message);

                    }
                } else {
                      error("图片上传失败");
                }
            }
        });
    }


图片上传成功处理

    /**
     * 图片上传成功
     * */
    private void success(String url,String thumb){
        PicBean bean = new PicBean();
        bean.setUrl(url);
        bean.setThumb(thumb);
        resultList.add(bean);
        ((Activity) context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (null != upLoadListener) {
                        if (resultList.size() == picList.size())
                            upLoadListener.upLoadResult(resultList);
               }
            }
        });
    }

图片上传失败处理

   /**
     * 图片上传失败
     * */
    private void error(final String message){
        ((Activity) context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                PicBean bean = new PicBean();
                bean.setUrl("");
                bean.setThumb("");
                resultList.add(bean);
                if (null != upLoadListener) {
                    if (resultList.size() == picList.size())
                         upLoadListener.upLoadError(message);
                }
            }
        });
    }

你可能感兴趣的:(多张图片,一张一张上传(处理结果那有点蠢))