Java传输多附件的表单

该代码段展示了一个Java客户端使用HttpPost上传文件至服务器的实现,包括文件流、消息和令牌信息。服务端接收到文件后,进行MD5校验、文件存储以及数据库操作。如果校验失败或写入数据库时出错,会返回相应错误信息。
摘要由CSDN通过智能技术生成

客户端

    public static String uploadFile(String remoteUrl,String messageInform,String filename,List<String> fileaddress) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        String result = null;
        HttpPost httpPost = null;
        InputStream is = null;
            try {
                for (String s : fileaddress) {
                    File file = new File(s);
                    is = new FileInputStream(file);
                    String fileName = file.getName();
                    httpPost = new HttpPost(remoteUrl);
                    builder.addBinaryBody("file", is, ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
                    builder.setCharset(Charset.forName("utf-8"));
                }
                ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
                StringBody stringBody = new StringBody(messageInform,contentType);
                builder.addPart("messageInform", stringBody);
                StringBody stringBody1 = new StringBody(filename,contentType);
                builder.addPart("filename", stringBody1);
                StringBody stringBody2 = new StringBody(token,contentType);
                builder.addPart("token",stringBody2);
                HttpEntity entity = builder.build();
                httpPost.setEntity(entity);
                HttpResponse response = httpClient.execute(httpPost);// 执行提交
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    // 将响应内容转换为字符串
                    result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
                    System.out.println(result);
                    JSONObject jsonObject = JSON.parseObject(result);
                    String success = jsonObject.get("code").toString();
                    if ("200".equals(success)){
                        //这里的值根据返回值动态获取
                        result = "200";
                    }else{
                        result = "500";
                    }
                }
            } catch (IOException e) {
                is.close();
                System.out.println(e.getMessage()+"1");
            } catch (Exception e) {
                System.out.println(e.getMessage()+"2");
            } finally {
                if (httpPost != null){
                    httpPost.releaseConnection();
                    is.close();
                }
                try {
                    httpClient.close();
                } catch (IOException e) {
                    System.out.println(e.getMessage()+"3");
                }finally {
                    httpClient.close();
                    is.close();
                }
            }



        return result;
    }

服务端

public AjaxResult remoteUpdateTest(@RequestPart("file") MultipartFile[] images
            ,@RequestPart("messageInform") String messageInform
            ,@RequestPart("filename") String filename
            ,@RequestPart("token") String token
    ) throws Exception {
        String mima = DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex("hello this is a message word".getBytes()).getBytes());
        System.out.println(mima);
        System.out.println(token);
        if (!mima.equals(token)){
            return AjaxResult.error("token错误");
        }
        List<Map> map = (List<Map>) JSONObject.parseObject(filename, List.class);
        MessageInform messageInform1 = (MessageInform) JSONObject.parseObject(messageInform,MessageInform.class);
        System.out.println(messageInform);
        List<Integer> flag = new LinkedList<>();
        String message = "失败";
        String filePath = acctchPath;
        System.out.println(messageInform1);
        for (MultipartFile file : images) {
           String oldname = file.getOriginalFilename();
//           File converFile = new File(file.getOriginalFilename());
//            String oldname = converFile.getName();
            for (Map map1 : map) {
                SAttach sAttach = new SAttach();
                sAttach.setAttachName((String)map1.get("ATTACHNAME"));
                sAttach.setId((String)map1.get("ID"));
                sAttach.setAttachPath((String)map1.get("ATTACHPATH"));
                sAttach.setUploadTime(new Date());
                sAttach.setOwnerId(messageInform1.getId());
                sAttach.setBusinessId(messageInform1.getId());
                sAttach.setSuffix(oldname.substring(oldname.lastIndexOf(".") + 1));
                sAttach.setOwnerName("检查执法系统");
                String showname = (String) map1.get("ID");
                int dot = oldname.indexOf(".");
                if ((dot >-1) && (dot < (oldname.length()))) {
                     String redirctName =  oldname.substring(0, dot);
                     if (redirctName.equals(showname)){
                         System.out.println((String)map1.get("ATTACHPATH"));
                         File newFile = new File(filePath+(String)map1.get("ATTACHPATH")+"/"+oldname);
                         if (!newFile.getParentFile().exists()){
                             newFile.getParentFile().mkdirs();
                         }
                         try {

                             System.out.println("进入方法");
                             file.transferTo(newFile);
                             Log.info("上传成功");
                             message = "成功";
                             sAttach.setAttachPath(filePath+(String)map1.get("ATTACHPATH")+"/"+oldname);
                             sAttach.setDomain("message_inform");
                             sAttach.setDelFlag("1");
                             sAttach.setFilesize(String.valueOf(newFile.length()));
                             sAttachMapper.insertSAttach(sAttach);
                         }catch (IllegalStateException e){
                             flag.add(0);
                             e.printStackTrace();
                         }catch (IOException e){
                             flag.add(0);
                             e.printStackTrace();
                         }
                     }
                }

            }
//            for (Map map1 : map) {
//
//                String showname = (String) map1.get("ID");
//                int dot = oldname.indexOf(".");
//                if ((dot >-1) && (dot < (filename.length()))) {
//                     String redirctName =  filename.substring(0, dot);
//                     if (redirctName.equals(showname)){
//
//                     }
//                }
//
//
//            }
                 }
        if(flag.size()==0){
            messageInformService.insert(messageInform1);
            return AjaxResult.success();
        }else {
            throw new Exception("写入数据库失败");
        }

    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值