Android multipart 上传文件到服务端

安卓端代码:

public static void sendFile(String filePath){
       //要发送的文件
       File file = new File(filePath);
       OkHttpClient client = new OkHttpClient.Builder().build();
       
       //构建multipart body
       MultipartBody body = new MultipartBody.Builder()
               .setType(MultipartBody.FORM)
               .addFormDataPart("username", "wjj")
               .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/jpeg"), file))
               .build();

       Request request = new Request.Builder()
               .headers(headerBuilder.build())
               .url("http://10.237.54.146:8866/test/uploadbin")
               .post(body)
               .build();

       Call call = client.newCall(request);
       call.enqueue(new Callback() {
           @Override
           public void onFailure(@NonNull Call call, @NonNull IOException e) {
               Log.e("wjj", "call res = " + "failed");
           }

           @Override
           public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                   Log.e("wjj", "response = " + response.body().string());
           }
       });

   }

springboot端代码

@PostMapping("/uploadbin")
   public String recvFile(MultipartHttpServletRequest request) throws Exception {

       FileInputStream sin = (FileInputStream) request.getFile("file").getInputStream();
       File file = new File("D:/Tmp/saved.jpg");
       FileOutputStream fos = new FileOutputStream(file);
       byte[] bytes = new byte[1024];
       int len = -1;
       while((len = sin.read(bytes)) != -1){
           fos.write(bytes, 0, len);
       }

       sin.close();
       fos.close();
       return "file len:" +  ", " + request.getContentType();
   }

Multipart中的其他数据是如何取出的?

比如这段:

在这里插入图片描述
其实也是通过读取流:

   byte[] bytes1 = request.getPart("username").getInputStream().readAllBytes();
   String s = new String(bytes1);
   System.out.println(s);




那么multipart中的文件名是如何取出的?

在这里插入图片描述
方法:

request.getFile("file").getOriginalFilename()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值