服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 关于文件上传MultipartBody的使用方法

关于文件上传MultipartBody的使用方法

2023-02-21 15:16Arcturis Java教程

这篇文章主要介绍了关于文件上传MultipartBody的使用方法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

文件上传MultipartBody的使用

最近有使用一个文件上传的功能,需要在请求中添加文件,一起传给服务器

Okhttp提供了这个文件添加然后上传的功能

下面给出核心的代码,然后分析一下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//多个文件上传,Filelist
    private static Request getFilesRequest(String url, List<File> files, Map<String, String> maps){
        MultipartBody.Builder builder=  new MultipartBody.Builder().setType(MultipartBody.FORM);
        if(maps==null){
            for(int i = 0;i < files.size();i++){
                builder.addPart( Headers.of("Content-Disposition", "form-data; name=\"file\";filename=\"file.jpg\""),
                        RequestBody.create(MediaType.parse("image/png"),files.get(i))
                ).build();
            }
        }else{
            for (String key : maps.keySet()) {
                String str = maps.get(key);
                builder.addFormDataPart(key,str );
            }
            for(int j = 0;j < files.size();j++){
                long fileSize = files.get(j).length();
                builder.addPart( Headers.of("Content-Disposition", "form-data; name=\"file\";filename=\"file.jpg\";filesize="+fileSize),
                        RequestBody.create(MediaType.parse("image/png"),files.get(j))
                );
            }
        }
        RequestBody body=builder.build();
        return   new Request.Builder().url(url).post(body).build();
    }

先说三个参数吧

  • 三个参数第一个是请求的URL
  • 第二个是Multipart的文件list
  • 第三个是headermap,就是请求的请求头params

首先通过Multipart的Builder模式实例化一个builder

其次如果Header的map为空则直接将file加入到part中

否则依次将headermap 和 file的list中的数据加入到Request中

完成后builder build 出来的MultipartBody 请求赋值给 RequestBody(Multipartbody继承了Requestbody)

之后将Request构建完成即可

?
1
Call call =mOkhttpClient.newCall(request);

然后就是用Okhttp 进行请求,请求方法略过

MultipartBody取出key,value数据,打印参数

MultipartBody打印参数比较麻烦

kotlin:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
if (requestBody is MultipartBody) {
           val params = mutableMapOf<String, String>()
           val files = mutableMapOf<String, String>()
           requestBody.parts().forEach {
               val body = it.body()
               it.headers()?.let {
                   val header = it.value(0)
                   val split = header.replace(" ", "").replace("\"", "").split(";")
                   when (split.size) {
                       2 -> {
                           //文本参数
                           val keys = split[1].split("=")
                           if (keys.size > 1 && body.contentLength() < 1024) {
                               val key = keys[1]
                               val buffer = Buffer()
                               body.writeTo(buffer)
                               val value = buffer.readUtf8()
                               params[key] = value
                           }
                       }
                       3 -> {
                           //文件
                           val fileKeys = split[1].split("=")
                           val fileKey = if (fileKeys.size > 1) {
                               fileKeys[1]
                           } else ""
                           val nameValue = split[2].split("=")
                           val fileName = if (nameValue.size > 1) nameValue[1] else ""
                           files[fileKey] = fileName
                       }
                   }
               }
           }
           println("文件-->$files")
           println("文本-->$params")
       }

java写法 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
if (requestBody instanceof MultipartBody) {
    MultipartBody body = (MultipartBody) requestBody;
    Map<String, String> params = new HashMap<>();
    Map<String, String> files = new HashMap<>();
    for (MultipartBody.Part part : body.parts()) {
        RequestBody body1 = part.body();
        Headers headers = part.headers();
        if (headers != null && headers.size() > 0) {
            String[] split = headers.value(0).replace(" ", "").replace("\"", "").split(";");
            if (split.length == 2) {
                //文本
                String[] keys = split[1].split("=");
                if (keys.length > 1 && body1.contentLength() < 1024) {
                    String key = keys[1];
                    String value = "";
                    Buffer buffer = new Buffer();
                    body.writeTo(buffer);
                    value = buffer.readUtf8();
                    params.put(key, value);
                }
            } else if (split.length == 3) {
                //文件
                String fileKey = "";
                String fileName = "";
                String[] keys = split[1].split("=");
                String[] names = split[2].split("=");
                if (keys.length > 1) fileKey = keys[1];
                if (names.length > 1) fileName = names[1];
                files.put(fileKey, fileName);
            }
        }
 
    }
    System.out.println("文本参数-->" + params);
    System.out.println("文件参数-->" + files);
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。 

原文链接:https://www.cnblogs.com/fengfenghuifei/p/6898201.html

延伸 · 阅读

精彩推荐