retrofit上传文件
时间: 2025-01-14 19:41:53 浏览: 47
### 使用 Retrofit 进行文件上传
在 Retrofit 2 中,`TypedFile` 类已经被移除,取而代之的是利用 `OkHttp` 库中的类来处理文件上传操作[^1]。下面是一个具体的例子展示如何通过 Retrofit 实现文件上传功能。
#### 创建 API 接口定义
首先需要创建一个接口用于描述 HTTP 请求方法,在此案例中为 POST 方法并指定路径以及参数:
```java
public interface FileUploadService {
@Multipart
@POST("/upload")
Call<ResponseBody> uploadImage(
@Part MultipartBody.Part file,
@Part("description") RequestBody description);
}
```
这里使用了 `@Multipart` 注解表明这是一个多部分表单请求;`@Part MultipartBody.Part file` 表示要上传的文件部分;`@Part("description") RequestBody description` 则是用来传递额外的信息比如图片说明等文字内容。
#### 准备待上传的数据
接着准备实际要发送给服务器的内容,包括文件本身和其他附加信息:
```java
// Create a file object from your image path.
File file = new File(imagePath);
// Create RequestBody instance from file
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
// Create MultipartBody.Part using file name as the key
MultipartBody.Part body = MultipartBody.Part.createFormData("picture", file.getName(), requestBody);
// Add another part within the multipart request containing a description string
String descriptionString = "This is some text describing my awesome picture!";
RequestBody description =
RequestBody.create(
MediaType.parse("text/plain"),
descriptionString);
```
上述代码片段展示了如何构建包含图像数据及其描述文本的消息体。注意设置合适的 MIME 类型以便接收端能够正确解析接收到的数据流。
#### 初始化 Retrofit 并执行网络请求
最后一步就是初始化 Retrofit 客户端并将之前定义好的服务实例化出来调用对应的方法发起真正的 HTTP 请求:
```java
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://yourserveraddress.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
FileUploadService service = retrofit.create(FileUploadService.class);
Call<ResponseBody> call = service.uploadImage(body, description);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
Log.v("UPLOAD", "success");
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("UPLOAD", "error:" + t.getMessage());
}
});
```
这段代码实现了向指定地址发送带有附件(即图片)和描述字符串的 POST 请求,并监听响应结果来进行相应的日志记录或其他业务逻辑处理。
阅读全文
相关推荐


















