在我的 kotlin 项目中,我使用 retrofit
它运作良好。
suspend fun createPlan(
context: Context?,
name: String,
file: File?
): ABC? {
val fileSignImage = file?.let {
MultipartBody.Part.createFormData(
"image",
it.getName(),
RequestBody.create("image/*".toMediaTypeOrNull(), it)
)
}
return RetrofitFactory.apiCall(context) {
RetrofitFactory.makeRetrofitService().createPlan(
name.toRequestBody("text/plain".toMediaTypeOrNull()),
fileSignImage
)
}}
改造服务
@Multipart
@POST("create_plan")
fun createPlan(
@Part("name") name: RequestBody,
@Part image: MultipartBody.Part?
): Deferred<Response<WebApiResponse.ABCs>>
如果我想使用
Chopper
,正确的做法是什么?这是我尝试过的
Future<Response> createPlan(
BuildContext context, String name,String path) async {
Response response;
try {
response = await _service.createPlan(
name,path);
return response;
} catch (e) {
rethrow;
}
}
服务
@Post(path: "create_plan")
@multipart
Future<Response> createPlan(
@Field('name') String name,@PartFile('image') String imagePath);
如何将 imagePath 转换为文件,以便我可以使用
Chopper
将其作为文件传递给服务器?任何人?
最佳答案
查看 Chopper 的文档,PartFile
注解支持三种数据类型:
List<int>
String
(path of your file)MultipartFile
(from package:http)
您当前正在使用
String
,但由于未知原因,它对您不起作用。第一个选项可能是最直接的,但第三个选项与您目前在 Retrofit 中的最相似,因此我们可以尝试一下。import 'package:http/http.dart';
...
Future<Response> createPlan(BuildContext context, String name, String path) async {
Response response;
try {
final bytes = (await File(path).readAsBytes()).toList();
final file = MultipartFile.fromBytes('image', bytes);
response = await _service.createPlan(
name,
file,
);
return response;
} catch (e) {
rethrow;
}
}
服务
@Post(path: "create_plan")
@multipart
Future<Response> createPlan(
@Field('name') String name,
@PartFile('image') MultipartFile image,
);
关于kotlin - 如何使用 Chopper 发送文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59988978/