android - 如何使用改造将图像发送到服务器
问题描述
我正在尝试使用改造、multipart/form-data 将图像发送到服务器。但我得到一个错误。
我试过用 Postman 发送图片,没问题。
@Multipart
@POST("requests/11006/history")
fun sendMessageWithImg(
@Header("X-Device-UDID") deviceUDID: String = "",
@Header("Authorization") token: String,
@Part image: MultipartBody.Part
): Call<ResponseBody>
private fun upload(fileUri: Uri) {
val tokenStorage = TokenStorage(this)
val token = tokenStorage.getToken()
val originalFile = FileUtils.getFile(this, fileUri)
val filePart = RequestBody.create(
MediaType.parse(contentResolver.getType(fileUri)),
originalFile)
val file: MultipartBody.Part = MultipartBody.Part.createFormData("image[]", originalFile.name, filePart)
val client = ApiService.create()
val call: Call<ResponseBody> = client
.sendMessageWithImg(
token = "Bearer $token",
image = file)
call.enqueue(object : Callback<ResponseBody>{
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
print(call)
}
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
print(response)
}
})
}
错误是 - 无法从 /fec0::9c04 连接到.30::681c:587(端口 443)。(端口 38630)10000 毫秒后
解决方案
试试这个代码
@Multipart
@POST("user/updateprofile")
Observable<ResponseBody> updateProfile(@Part("user_id") RequestBody id,
@Part("full_name") RequestBody fullName,
@Part MultipartBody.Part image,
@Part("other") RequestBody other);
//pass it like this
File file = new File("/storage/emulated/0/Download/Corrections 6.jpg");
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("image", file.getName(), requestFile);
// add another part within the multipart request
RequestBody fullName =
RequestBody.create(MediaType.parse("multipart/form-data"), "Your Name");
service.updateProfile(id, fullName, body, other);
推荐阅读
- css - 不能将 div 排列在另一个之下
- python - 如何将时空数据重塑为 lstm 输入?
- xpages - 通过复合数据上的 getComponent 获取价值
- angular - ngStyle 函数在条件下运行
- python - 无法将 anaconda 上的 python 包更新到最新版本
- django - Django - 如何创建由外键分隔的复选框表单
- java - 字谜检查器来解决管测验
- reactjs - 使用 `react-apollo-hooks` 和 `useSubscription` 钩子
- typescript - 定义相互依赖的泛型类型`map: Map
(参数:部分 ) => T)>;` - javascript - How to run the same function (but class changes) on multiple IDs jQuery