[英]upload picture to server android
我必須使用Retrofit2我的API捕獲圖像並將其上傳到服務器
@Multipart
@POST("photo/")
Call<NetWorkResponse<String>> uploadPhoto(@Header("Authorization") String token,
@Part("category") String category,
@Part MultipartBody.Part photo);
我上傳照片的方法
public static void uploadPhoto(String nfToken, String category, File photoFile) {
RequestBody filePart = RequestBody.create(MediaType.parse("image/jpeg"), photoFile);
MultipartBody.Part file = MultipartBody.Part.createFormData("photo", photoFile.getName(), filePart);
Call<NetWorkResponse<String>> call = nfApi.uploadPhoto(nfToken, category, file);
call.enqueue(new Callback<NetWorkResponse<String>>() {
@Override
public void onResponse(Call<NFNetWorkResponse<String>> call, Response<NetWorkResponse<String>> response) {
if (response.isSuccessful()) {
NetWorkResponse<String> netWorkResponse = response.body();
} else {
}
}
@Override
public void onFailure(Call<NetWorkResponse<String>> call, Throwable t) {
}
});
}
我的照片文件Uri: file:///storage/emulated/0/Pictures/Food/IMG_20170731_094856_2128319239.jpg
當我將文件上傳到服務器時,出現錯誤請求“錯誤請求”,代碼為400。這可能表明我的參數有誤,但是我很確定這沒有錯。 我猜圖片有問題,MediaType.parse(“ image / jpeg”)有問題
相反,應該是:
File f = new File(mCurrentPhotoPath);
Uri pictureUri = Uri.fromFile(f);
String contentType = getContentResolver().getType(pictureUri);
MediaType.parse(contentType)
但是問題是Uri路徑是file://而不是content://,所以contentType為null
知道我將照片上傳到服務器時怎么了
代替照片文件URL file:///storage/emulated/0/Pictures/Food/IMG_20170731_094856_2128319239.jpg
通過這個/storage/emulated/0/Pictures/Food/IMG_20170731_094856_2128319239.jpg
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.