Mr.Smile填坑记——POST上传文件(图片、视频等)

MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);

builder.addFormDataPart("name", uploadRequest.getZipFileName().replace(".zip", ""));
String zipFilePath = uploadRequest.getZipFilePath();
File file = new File(zipFilePath);
String fileName = file.getName();
RequestBody requestBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
builder.addFormDataPart("bundle", uploadRequest.getZipFileName(), requestBody);

UploadResult uploadResult = new UploadResult();
try {
    Request request = new Request.Builder()
            .url(uploadUrl)
            .header("Authorization", "Bearer "+uploadRequest.getToken())		//用于Oauth2,网络认证
            .addHeader("Content-Length", ""+requestBody.contentLength())
            .post(builder.build())
            .build();

    OkHttpClient client = new OkHttpClient();
    Response response = client.newCall(request).execute();
 
  
 
  
addFormDataPart这个方法是对addPart方法的封装,查看源码便可获知,
之前有人在网上说,参数用addFormDataPart,文件用addPart,其实都可以使用前者,并且里面直接传入键值对
更加的简单明了
 
 

你可能感兴趣的:(填坑)