OkHttp多文件上传

web端接口

 /**
     * 创建文件(多个)(via app)
     * @param token
     * @param files
     * 文件信息,已经转为JSON字符串传入。
     * @param arrfile
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "createfilesviapp", method = {RequestMethod.GET, RequestMethod.POST})
    public ReturnObject createFilesViapp (String token, String files,
                                          @RequestParam("arrfile") MultipartFile[] arrfile) {
        ReturnObject ro = new ReturnObject();
        ReturnState rs = new ReturnState();

        try {
            List<Map> filelist = svcFile.createFiles(files, arrfile, svcUser.getUseridByToken(token));
            if(filelist != null){
                ro.setState(rs.setSuccessCode(Constant.RSINTCODE_SUCCESS, null));
                ro.setData(filelist);
            }else {
                ro.setState(rs.setFailCode(Constant.RSINTCODE_FAIL, null));
            }

        }catch (Exception e) {
            LogService.error(e.getMessage());
            ro.setState(rs.setFailCode(Constant.RSINTCODE_FAIL_EXCEPTION, "出现异常!"));
        }

        return ro;
    }
/**
     * 创建文件(可批量创建)
     * @param files
     * 文件信息,已经转为JSON字符串传入。
     * @param arrfile
     * @param userid
     * @return
     * 返回创建的文件信息
     */
    @Transactional
    public List<Map> createFiles(String files, MultipartFile[] arrfile, long userid) {
        int i,n;
        Long fwbid;
        Object val;
        JSONArray jsnarr;
        JSONObject jsnobj;
        FilewbEntity   efilewb;

        jsnarr = JSONArray.fromObject(files);
        n= jsnarr.size();
        List<FilewbEntity> lstFile = new ArrayList<FilewbEntity>();
        ArrayList<Long> alFwbid = new ArrayList<Long>();

        try {
            for(i=0; i<n; i++){
                efilewb = new FilewbEntity();
                efilewb.setCrtrid(userid);

                jsnobj = jsnarr.getJSONObject(i);

                if(null != (val = jsnobj.get("fwbid")))
                    efilewb.setFwbid(Long.valueOf(val.toString()));

                if(null != (val = jsnobj.get("state"))){
                    efilewb.setState(Byte.valueOf(val.toString()));
                }else {
                    efilewb.setState(Constant.STATE_USABLE);
                }

                if(null != (val = jsnobj.get("name")))
                    efilewb.setName(val.toString());

                if(null != (val = jsnobj.get("mediatype"))){
                    efilewb.setMediatype(Byte.valueOf(val.toString()));
                }else {
                    efilewb.setMediatype(Constant.MEDIATYPE_UNKNOWN);
                }

                if(null != (val = jsnobj.get("filetype"))){
                    efilewb.setFiletype(Byte.valueOf(val.toString()));
                }else {
                    efilewb.setFiletype(Constant.FILETYPE_UNKNOWN);
                }


                /* 这些字段不允许用户编辑,但注释保留。>>>

                if(null != (val = jsnobj.get("crtrid")))
                    efilewb.setCrtrid(Long.valueOf(val.toString()));
                if(null != (val = jsnobj.get("verno")))
                    efilewb.setVerno(Integer.valueOf(val.toString()));
                if(null != (val = jsnobj.get("crttime"))){
                    Date date = null;
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    date = sdf.parse(val.toString());
                    efilewb.setCrttime(date);
                }
                if(null != (val = jsnobj.get("edittime"))){
                    Date date = null;
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    date = sdf.parse(val.toString());
                    efilewb.setEdittime(date);
                }

                */

                if(null != (val = jsnobj.get("fldrid")))
                    efilewb.setFldrid(Long.valueOf(val.toString()));

                if(null != (val = jsnobj.get("supfwbid")))
                    efilewb.setSupfwbid(Long.valueOf(val.toString()));

                lstFile.add(efilewb);
            }

            if(n != daoFile.insertBatch(lstFile)){
                // 回滚事务
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return null;
            }
        }catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return null;
        }

        //
        // 保存文件到阿里云。

        for(i=0; i<n; i++){
            fwbid = lstFile.get(i).getFwbid();
            alFwbid.add(fwbid);
            saveFile(fwbid, arrfile[i], userid);
        }

        return daoFile.selectFiles(alFwbid.toArray(new Long[alFwbid.size()]), daoRepos.selectByPrimaryKey(Constant.REPOSID_WRITING).getAddress());
    }

android代码

private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
private static final OkHttpClient client = new OkHttpClient();
/**
     * 上传多张图片
     * @param fileurls 本地文件路径集合的json字符串
     * @param requesturl web接口路径
     * @param token
     * @param folderid 上传到的文件夹ID
     * @param filename 文件名称集合的json字符串
     * @return
     */
    public static String uploadImgs(String fileurls, String requesturl, String token, String folderid, String filename) {
        String result = null;
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        List<Map> fileweb = new ArrayList<>();
        try {
            JSONArray jafileurls = new JSONArray(fileurls);
            JSONArray jafilename = new JSONArray(filename);
            if(jafileurls.length() > 0){
                for(int i = 0 ; i < jafileurls.length() ; i++){
                    File file = new File(jafileurls.get(i).toString());
                    builder.addFormDataPart("arrfile", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));

                    Map jo = new HashMap();
                    jo.put("state","1");
                    jo.put("name",jafilename.get(i).toString());
                    jo.put("mediatype","2");
                    jo.put("filetype","5");
                    jo.put("supfwbid","0");
                    jo.put("fldrid",folderid);
                    fileweb.add(jo);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        //添加其它信息
        builder.addFormDataPart("token",token);
        builder.addFormDataPart("files", new JSONArray(fileweb).toString());
        MultipartBody requestBody = builder.build();
        //构建请求
        Request request = new Request.Builder()
                .url(requesturl)//地址
                .post(requestBody)//添加请求体
                .build();

        Response response = null;
        try {
            response = client.newCall(request).execute();
            result = response.body().string();
            Log.d("====请求结果====", result);
            response.body().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值