0


java代码实现postman表单传输文件数据到第三方API

最近工作做遇到的问题:

            需求:前端传递一个附件ID接收到之后去查询数据库表中的文件附件ID通过工具类的方法获取到文件流,再把文件数据和文件存储地址 传给第三方API存储到指定的位置。

            问题:获取到文件流发送过去发现对方不能接收流的数据,只能接收完整的File数据,最后我要先把获取到的流下载到本地,再把下载的完整的文件传递给第三方API(难点:java代码模仿postman发送表单数据,)

/**
     * 接收"杰"提供的  {文件}
     * 调用"平"的API传递 文件
     *
     * @param request  HttpServletRequest 对象
     * @param response HttpServletResponse 对象
     * @return String
     */
    @POST
    @Path("/sendPartInfo")
    @Produces({MediaType.APPLICATION_JSON})
    public String sendPartInfo(@Context HttpServletRequest request, @Context HttpServletResponse response) {

        // 获取上传的文件id
        Map<String, Object> map = ParamUtil.request2Map(request);
        Object id = map.get("id");
//        Object address = map.get("address");
//        String addressString = (String) address;

        //查询imagefileid的值
        HashMap<String, String> image = new HashMap<>();
        RecordSet rs = new RecordSet();
        String sql = "select  * from DocImageFile where DOCID =?";
        rs.executeQuery(sql, id);
        while (rs.next()) {
            String imagefileid = rs.getString("imagefileid");
            image.put("imagefileid", imagefileid);
        }
        String imagefileid = image.get("imagefileid");
        int imageId = Integer.parseInt(imagefileid);

        //创建返回集合
        HashMap<Object, Object> map1 = new HashMap<>();

        // 通过附件id获取文件流
        InputStream inputStreamByImagefileId = FileStreamUtil.getInputStreamByImagefileId(imageId);

        String fileNameByImagefileId = FileStreamUtil.getFileNameByImagefileId(imageId);

        if (inputStreamByImagefileId == null) {

            map1.put("msg", "查询到的文件流为空");
            map1.put("code", "-1");
            return JSONObject.toJSONString(map1); // 返回文件流为空的信息
        }
//        String savePath = "D:\\域文件夹" + addressString + fileNameByImagefileId;  // 文件保存路径
        String savePath = "D:\\域文件夹\\3_部品承认" + fileNameByImagefileId;  // 文件保存路径
        try {
            FileOutputStream outputStream = new FileOutputStream(savePath);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStreamByImagefileId.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
            map1.put("code", "1");
            map1.put("msg", "1.文件下载到本地已完成");

            System.out.println(JSONObject.toJSONString(map1));

        } catch (IOException e) {
            map1.put("code", "-1");
            map1.put("msg", "文件下载失败,1.文件下载到本地异常");
            System.out.println(JSONObject.toJSONString(map1));
        }

        String apiUrl = "http://192.168.0.191:3000/upload";
        String fileParamName = "file[0]"; // 文件参数的名称
        String uploadPath = "\\3_部品承认\\3_11_发行受控档"; // 文本参数的值
        String textParamName = "uploadPath"; // 文本参数的名称

        try {
            URL url = new URL(apiUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);

            // 设置请求头
            String boundary = "<calculated when request is sent>";
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            OutputStream outputStream = connection.getOutputStream();
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8), true);

            // 写入文本参数
            writer.append("--").append(boundary).append("\r\n");
            writer.append("Content-Disposition: form-data; name=\"").append(textParamName).append("\"").append("\r\n");
            writer.append("\r\n");
            writer.append(uploadPath).append("\r\n");

            // 写入文件参数
            writer.append("--").append(boundary).append("\r\n");
            writer.append("Content-Disposition: form-data; name=\"").append(fileParamName).append("\"; filename=\"").append(new File(savePath).getName()).append("\"").append("\r\n");
            writer.append("Content-Type: application/octet-stream").append("\r\n");
            writer.append("\r\n");
            writer.flush();

            // 写入文件内容
            try (FileInputStream fileInputStream = new FileInputStream(savePath)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }

            outputStream.flush();

            // 写入结束标记
            writer.append("\r\n");
            writer.append("--").append(boundary).append("--").append("\r\n");
            writer.flush();

            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应数据
                InputStream inputStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                StringBuilder respons = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    respons.append(line);
                }
                reader.close();

                map1.put("code", "1");
                map1.put("msg", "上传成功");

            } else {
                map1.put("code", "-1");
                map1.put("msg", "上传失败,文件保存异常");
            }

            connection.disconnect();
        } catch (IOException e) {
            Map<String, Object> map2 = new HashMap<>();
            map2.put("msg", "连接异常");
            map2.put("code", "0");
            return JSONObject.toJSONString(map2);
        }

        //删除本地下载的文件
        File file = new File(savePath);
        if (file.isFile()) {
            if (file.delete()) {
                System.out.println("已删除文件: " + file.getName());
            } else {
                System.out.println("无法删除文件: " + file.getName());
            }
        } else {
            System.out.println("指定路径不是一个文件");
        }

        return JSONObject.toJSONString(map1);
    }

本文转载自: https://blog.csdn.net/id288499173/article/details/134076501
版权归原作者 小闫66 所有, 如有侵权,请联系我们删除。

“java代码实现postman表单传输文件数据到第三方API”的评论:

还没有评论