java模拟formdata文件上传

该博客详细介绍了如何实现将本地文件上传到远程接口的过程,包括设置HTTP连接、请求头、请求正文,以及处理文件流。文件上传后,本地临时文件会被删除。同时,文章还展示了如何处理上传后的返回数据,并在成功上传后读取并返回文件地址。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件上传到远程接口

本地文件是暂存的,上传后要删除

fileTemporaryStoragePath 是文件在本地的存储路径

fileTempName 是文件的名称+类型,类似test.pdf

fileTemporaryStoragePath + fileTempName,是文件全路径

yxFile 是接口返回数据的接收对象

 

 /**
     * 文件上传到远程
     * 上传后本地被删除
     *
     * @param fileTempName xxxx.pdf
     * @return 上传到接口后的返回数据(文件地址)
     */
    @Override
    public String uploadFile(String fileTempName) {
        log.info("上传文件:{}", fileTempName);

        String yxFile = "";

        String tempFilePath = fileTemporaryStoragePath + fileTempName;
        File tempFile = new File(tempFilePath);

        OutputStream out = null;
        BufferedReader reader = null;
        try {

            if (!tempFile.exists() || !tempFile.isFile()) {
                throw new IOException("文件不存在");
            }
            URL urlObj = new URL(officialWebsiteUploadFileUrl);
            // 连接
            HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
            /**
             * 设置关键值
             */
            con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false); // post方式不能使用缓存
            // 设置请求头信息
            con.setRequestProperty("charset", "UTF-8");
            con.setRequestProperty("accept", "application/json");
            con.setRequestProperty("Content-length", String.valueOf(tempFile.length()));
            // 设置边界
            String BOUNDARY = "----------" + System.currentTimeMillis();
            con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            // 请求正文信息
            // 第一部分:
            StringBuilder sb = new StringBuilder();
            sb.append("--"); // 必须多两道线
            sb.append(BOUNDARY);
            sb.append("\r\n");
            sb.append("Content-Disposition: form-data;name=\"file\";filename=\""
                    + tempFile.getName() + "\"\r\n");
            sb.append("Content-Type:application/octet-stream\r\n\r\n");
            byte[] head = sb.toString().getBytes("utf-8");
            // 获得输出流
            out = new DataOutputStream(con.getOutputStream());
            // 输出表头
            out.write(head);
            // 文件正文部分
            // 把文件已流文件的方式 推入到url中
            DataInputStream in = new DataInputStream(new FileInputStream(tempFile));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            in.close();
            // 结尾部分
            byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
            out.write(foot);
            out.flush();
            out.close();
            out = null;

            //返回值
            int resultCode = con.getResponseCode();
            String msg = con.getResponseMessage();

            if (200 != resultCode) {
                log.info("返回值不是200,文件上传到远程接口异常:{}", msg);
            } else {
                log.info("返回值是200,文件上传到远程接口成功:{}", msg);

                // 读取返回数据
                StringBuffer strBuf = new StringBuffer();
                reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    strBuf.append(line).append("\n");
                }
                yxFile = strBuf.toString();
                reader.close();
                reader = null;
            }


            //删除本地文件
            tempFile.delete();

        } catch (Exception e) {
            log.info("文件上传到远程接口异常:{}", e.getMessage());
        } finally {
            //关闭流
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
        return yxFile;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值