将文件上传到服务器的通用方法

本文介绍了一个用于将字节流上传至指定URL的Java工具类。该工具使用OkHttp库实现HTTP POST请求,并能够处理文件上传过程中的各种异常。

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

将字节流上传到目标地址的工具类
@Component
public class MyHttpClient
{
    public void recordInfo(String goalUrl, byte[] bytes) throws Exception
    {
        long st = System.currentTimeMillis();
        String boundary="---*DFSE084*---";

        MultipartBody.Builder builder=new MultipartBody.Builder(boundary).setType(MultipartBody.FORM);
        builder.addPart(Headers.of("Content-Disposition","form-data; name=\"binary\"; filename=\"qrcode.jpg\""),
                RequestBody.create(MediaType.parse("application/octet-stream"), bytes));

        RequestBody body=builder.build();

        Request req = new Request.Builder().url(goalUrl).post(body).build();

        OkHttpClient client=new OkHttpClient();

        try(okhttp3.Response resp=client.newCall(req).execute()){
            resp.body().string();
            long et = System.currentTimeMillis() - st;
            com.to8to.rpc.utils.LogUtils.logger().info("将二维码上传到图片服务器,请求耗时:={}",et);
        } catch (IOException ex) {
            LogUtils.logger().warn("转存失败! 错误信息为:{}", LogUtils.logStackTrace(ex));
        }
    }
}

代码验证:

public static void main(String[] args) {
    
        String targetPath = "http://pic.xx.com:40009/erp/test.pdf";
        Path path = Paths.get("D:\\test.pdf");
        try {
            byte[] bytes = Files.readAllBytes(path);
            recordInfo(targetPath, bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

拨测方法验证:

curl -X PUT -H "Cache-Control: no-cache" -H "Postman-Token: 82f39c8b-1d33-caee-c25b-f6af45431e9d" -H "Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" -F "binary=@[这里是文件路径]" "http://192.168.1.34:40009/qrcode/hmm/feedback_porject.png"
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值