使用okhttp multipart将图像从Android上传到服务器

时间:2019-01-17 05:18:57

标签: android

这是我从照片库获取图像的方式:

`export interface Iposts {
    id :number;
    name:string;
    icon:string;
    shortDesc:string;
    topic_id:string;

}`

这是我尝试上传的方式:

private void presentPhotoSelector() {
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");
    startActivityForResult(intent, 0);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 0 && resultCode == Activity.RESULT_OK && data != null) {
        mSelectedPhotoUri = data.getData();
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), mSelectedPhotoUri);
            photoCircleImageView.setImageBitmap(bitmap);
            photoCircleImageView.setVisibility(View.VISIBLE);
            selectPhotoButton.setVisibility(View.INVISIBLE);
            uploadImageToServer(mSelectedPhotoUri);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这不起作用,加载程序永不停止旋转,并且在服务器端出现此错误:public class JSONResponse { boolean userUploadedProfileImage; User user; } private void uploadImageToServer(Uri selectedPhotoUri) { if (selectedPhotoUri == null) { Log.d(TAG, "uploadImageToServer: selectedPhotoUri is null"); return; } if (!AuthService.getInstance(mContext).isLoggedIn()) { Log.d(TAG, "uploadImageToServer: User not logged in"); return; } showLoading("Laster opp bilde...", "Vennligst vent mens prosess foregår"); File file = new File(selectedPhotoUri.getPath()); final MediaType MEDIA_TYPE_JPG = MediaType.parse("image/jpeg"); OkHttpClient okHttpClient = new OkHttpClient(); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", "image.jpg", RequestBody.create(MEDIA_TYPE_JPG, file)) .build(); Request request = new Request.Builder() .header("Authorization", "Bearer " + AuthService.getInstance(mContext).getToken()) .url(Config.URL + "/api/user/upload-profile-image") .post(requestBody) .build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { hideLoading(); } }); Log.d(TAG, "onFailure: response failed: " + e.getLocalizedMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { getActivity().runOnUiThread(new Runnable() { @Override public void run() { hideLoading(); } }); String responseBodyString = response.body().string(); Log.d(TAG, "onResponse: responseBodyString: " + responseBodyString); Gson gson = new Gson(); SettingsFragment.JSONResponse jsonResponse = gson.fromJson(responseBodyString, SettingsFragment.JSONResponse.class); if (jsonResponse != null) { UserService.getInstance(mContext).setMyUser(jsonResponse.user); Log.d(TAG, "onResponse: jsonResponse.userUploadedProfileImage: " + jsonResponse.userUploadedProfileImage); Log.d(TAG, "onResponse: jsonResponse.user: " + jsonResponse.user.toString()); } } }); }

但是,如果我将上面的代码更改为:

multipart: NextPart: client disconnected

收件人:

File file = new File(selectedPhotoUri.getPath());

然后请求成功,但是,当我尝试在浏览器上打开图像时,它显示“图像无法显示,因为它包含错误”。当我查看数据库时,可以看到它将其mime类型解释为:application / octet-stream,而不是image / jpeg。

我被困住了,我不知道该怎么办。

我现在在控制台上收到此错误:String file = selectedPhotoUri.getPath();

如果有帮助,我正在模拟器上运行它。

1 个答案:

答案 0 :(得分:0)

一种方法是: 您必须将Bitmap转换为Base64(String)并将该base64发送到服务器。