multipart/form-data

本文介绍如何使用OkHttp3库实现文件上传功能,包括如何构造MultipartBody以支持文件和参数混合上传,并展示了具体的代码实现及关键步骤。

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

在使用okhttp3 进行文件上传的时候,我们会使用多种类型表单的格式进行上传,因为我们不仅要上传文件File,还会附带一些参数过去。

下面就是okhttp上传的代码

 try {
            //补全请求地址
            String requestUrl = String.format("%s%s", HttpRequestBase.DEFAULT_HTTP_HOST_ADDRESS, url);
            LogUtils.d(TAG , "requestUrl == " + requestUrl);
            MultipartBody.Builder builder = new MultipartBody.Builder();
            //设置类型
            builder.setType(MultipartBody.FORM);
            //追加参数
            for (String key : paramsMap.keySet()) {
                Object object = paramsMap.get(key);
                if (!(object instanceof File)) {
                    builder.addFormDataPart(key, object.toString());
                } else {
                    File file = (File) object;
                    builder.addFormDataPart(key, file.getName(),  createProgressRequestBody(MEDIA_OBJECT_STREAM, file, callback));
                }
            }
            //创建RequestBody
            RequestBody body = builder.build();
            //创建Request
            final Request request = new Request.Builder().url(requestUrl).post(body).build();
            //单独设置参数 比如读取超时时间
            final Call call = mOkHttpClient.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    LogUtils.e(TAG, e.toString());
                    sendFailedStringCallback(call.request(), e, callback);
                }

                @Override
                public void onResponse(Call call, Response response) {

                    try {
                        final String string = response.body().string();
                        LogUtils.d(TAG , " response body " + string);
                        if (callback.mType == String.class) {
                            sendSuccessResultCallback(string, callback);
                        } else {
                            Object o = mGson.fromJson(string, callback.mType);
                            sendSuccessResultCallback(o, callback);
                        }


                    } catch (IOException e) {
                        sendFailedStringCallback(response.request(), e, callback);
                    } catch (com.google.gson.JsonParseException e)//Json解析的错误
                    {
                        sendFailedStringCallback(response.request(), e, callback);
                    }

                }
            });
        } catch (Exception e) {
            LogUtils.e(TAG, e.toString());
        }

public static final MediaType FORM = MediaType.parse("multipart/form-data");






从上面可以看出,有个boundary 分隔符,是用来进行内容的分割如文件内容和文本内容。这个boundary 的生成
public Builder() {
      this(UUID.randomUUID().toString());
    }

    public Builder(String boundary) {
      this.boundary = ByteString.encodeUtf8(boundary);
    }
生成一个唯一的Id。


 public static Part createFormData(String name, String filename, RequestBody body) {
      if (name == null) {
        throw new NullPointerException("name == null");
      }
      StringBuilder disposition = new StringBuilder("form-data; name=");
      appendQuotedString(disposition, name);

      if (filename != null) {
        disposition.append("; filename=");
        appendQuotedString(disposition, filename);
      }

      return create(Headers.of("Content-Disposition", disposition.toString()), body);
    }

这段代码就是生成multipart/form-data 请求体,name 是server端对应的字段,filename 是文件的名称,content-type 是 octet-stream 表明他就是一个字节流,浏览器默认处理字节流的方式就是下载。content-type 这个类型需要与server端的配置是一致的,否则不能成功。
下面是部分上传类型

'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg', 'image/png','application/msword','application/vnd.ms-excel',
'image/bmp','text/plain','application/octet-stream','image/x-png','application/x-shockwave-flash','audio/mpeg','audio/x-ms-wma',
'application/x-zip-compressed'





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值