android 如何在Kotlin中使用http请求上传图片到服务器?

uujelgoq  于 2022-12-02  发布在  Android
关注(0)|答案(4)|浏览(370)

我已经编写了使用Kotlin将图像上传到服务器的代码,也就是说,用户通过相机拍摄一张照片,然后在imageView中显示图像,当用户单击发送按钮时,我希望将ImageView中的图像发送到服务器,但我不知道如何将ImageView中的图像更改为可以发送到服务器的文件。
我已经设计了代码来捕获图像,并设置图像视图中的图像预览,但没有得到想法上传到服务器使用http请求。
打开相机并将图像设置为imageview:

private fun openCamera(){

    val values = ContentValues()

    values.put(MediaStore.Images.Media.TITLE, "New Picture")

    values.put(MediaStore.Images.Media.DESCRIPTION, "From Camera")

    private fun openCamera() {
    val values = ContentValues()
    values.put(MediaStore.Images.Media.TITLE, "New Picture")
    values.put(MediaStore.Images.Media.DESCRIPTION, "From Camera")
    image_uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)

    val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri)
    startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE)
}

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {

    when (requestCode) {
        PERMISSION_CODE_CAM -> {
            if (grantResults.size!! > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openCamera()
            } else {
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if (resultCode == Activity.RESULT_OK && resultCode == IMAGE_CAPTURE_CODE) {
        imageView.setImageURI(image_uri)
    }

}

我想上传图片到服务器使用http请求,我得到了许多代码在java中,但没有在Kotlin。我没有得到任何想法上传在kotlin。

kadbb459

kadbb4591#

由于这个问题仍然是开放的。我们可以使用OKHTTP库,这是非常容易使用,我们必须写非常少的代码。在这里我写了一个详细的文章的主题
Upload Image or File to Server in Android Kotlin
我不打算再复制相同的代码,我已经写了一个UploadUtility类。只要从上面的链接复制到你的项目中,它就会做剩下的事情。

rsaldnfx

rsaldnfx2#

Api接口

@Multipart
@POST("your_url")
suspend fun uploadImage(
    @Part file:MultipartBody.Part
): Response<String>

Kotlin码

val file: File = ImagePicker.getFile(data)!!

        val requestFile =RequestBody.create("multipart/form-data".toMediaTypeOrNull(),file)
        val requestFile=RequestBody.create(MediaType.parse("image/*"),file)
        val body = MultipartBody.Part.createFormData("profile_picture", file.name, requestFile)
        uploadImage(body)
jtoj6r0c

jtoj6r0c3#

这是图像上传使用Kotlin改造代码100%工作

private fun UploedImage(User_id:String , newfile: File) {
        Commons.showProgressDialog(this@StoreDetailActivity)

       
        //creating a file
        var requestFile: RequestBody? = null
        var document: MultipartBody.Part
        var ImageUloloadgetCall: Call<ImageUloloadgetUrlModel?>? = null
        if (newfile != null) {
            val MEDIA_TYPE_IMAGE = "image/*".toMediaTypeOrNull()

            requestFile = create(MEDIA_TYPE_IMAGE, newfile)

            document = createFormData(
                "image",
                newfile.getName(),
                requestFile
            )

            val userId= create("text/plain".toMediaTypeOrNull(), User_id)

            ImageUloloadgetCall = getApiInstance().ImageUpload(
                alldata,
                document
            )
        }
        ImageUloloadgetCall!!.enqueue(object : Callback<ImageUloloadgetUrlModel?> {
            override fun onResponse(
                call: Call<ImageUloloadgetUrlModel?>,
                response: Response<ImageUloloadgetUrlModel?>
            ) {
                dismissProgressDialog()
                if (!response.isSuccessful()) {
                    Log.d(
                        TAG,
                        "onResponse: fail " + response.code()
                    )
                    Toast.makeText(
                        this@StoreDetailActivity,
                        "" + response.message(),
                        Toast.LENGTH_SHORT
                    ).show()
                    return
                }
                Log.d(
                    TAG,
                    "onResponse: success" + response.code() + response.body()
                )
                if (response.body() != null) {
                    var imageUloloadgetUrlModel: ImageUloloadgetUrlModel? = null
                    try {
                        imageUloloadgetUrlModel = response.body()


                         
                    } catch (e: Exception) {
                        Toast.makeText(
                            this@StoreDetailActivity,
                            "Error in response",
                            Toast.LENGTH_SHORT
                        ).show()
                        return
                    }
                } else {
                    Toast.makeText(
                        this@StoreDetailActivity,
                        "Invalid response from server",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }

            override fun onFailure(call: Call<ImageUloloadgetUrlModel?>, t: Throwable) {
                dismissProgressDialog()
            }
        })
    }
oknrviil

oknrviil4#

您可以使用以下功能通过相机捕捉图像:

public static Uri getTakenPictureUri(Context mContext, Intent data) {
    Uri selectedImage = data.getData();
    String[] filePathColumn = {MediaStore.Images.Media.DATA};

    Cursor cursor = mContext.getContentResolver().query(selectedImage,
            filePathColumn, null, null, null);
    cursor.moveToFirst();

    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    String picturePath = cursor.getString(columnIndex);
    cursor.close();

    picturePath = "file://" + picturePath;
    LogHelper.trace("Selected file uri:" + picturePath);

    return Uri.parse(picturePath);
}

public static File createImageFile() throws IOException {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = MyPharmacy.getmInstance().getExternalCacheDir();
    LogHelper.trace("createImageFile:" + storageDir.getAbsolutePath());
    File image = File.createTempFile(
            imageFileName,
            ".jpg",
            storageDir
    );
    return image;
}

public static File openCamera(Activity mActivity, int requestCode) {
    Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    try {
        File photoFile = createImageFile();
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(MyPharmacy.getmInstance(), BuildConfig.APPLICATION_ID + ".provider", photoFile);
            camera.putExtra(MediaStore.EXTRA_OUTPUT,
                    photoURI);
            if (camera.resolveActivity(mActivity.getPackageManager()) != null) {
                mActivity.startActivityForResult(camera, requestCode);
                return photoFile;
            }
        }
    } catch (IOException ex) {
    }
    return null;
}

public static File openCamera(Fragment fragment, int requestCode) {
    Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    try {
        File photoFile = createImageFile();
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(MyPharmacy.getmInstance(), BuildConfig.APPLICATION_ID + ".provider", photoFile);
            camera.putExtra(MediaStore.EXTRA_OUTPUT,
                    photoURI);
            if (camera.resolveActivity(fragment.getActivity().getPackageManager()) != null) {
                fragment.startActivityForResult(camera, requestCode);
                return photoFile;
            }
        }
    } catch (IOException ex) {
    }
    return null;
}

然后使用以下代码通过改装上传

public static void uploadImage(final String filePath,
                                           final String token,
                                           final APIResponseCallback<UploadResponse> cb) {
    if (filePath != null && !filePath.isEmpty()) {
        final File file = new File(filePath);
        if (file.exists()) {

            Glide.with(App.getmInstance().getContext()).load(file).asBitmap().override(700, 700).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                    OutputStream os = null;
                    try {
                        String realPath = StorageHelper.getRealPathFromUri(App.getmInstance().getContext(), Uri.fromFile(file));
                        os = new BufferedOutputStream(new FileOutputStream(file));
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, os);
                        os.flush();
                        os.close();
                    } catch (java.io.IOException e) {
                        e.printStackTrace();
                    }

                    if (file != null) {
                        // creates RequestBody instance from file
                        RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
                        // MultipartBody.Part is used to send also the actual filename
                        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
                        // adds another part within the multipart request
                        String descriptionString = "Image";
                        RequestBody description = RequestBody.create(okhttp3.MultipartBody.FORM, descriptionString);
                        // executes the request
                        ServiceGenerator.getAPIServices().uploadImage(body, description, token).enqueue(new Callback<UploadResponse>() {
                            @Override
                            public void onResponse(Call<UploadResponse> call, Response<UploadResponse> response) {
                                if (response.isSuccessful()) {
                                    cb.onSuccess(response.body());
                                } else {
                                    checkError(response, token);
                                }
                            }

                            @Override
                            public void onFailure(Call<UploadResponse> call, Throwable t) {
                                cb.onError(t);
                            }
                        });
                    }
                }
            });
        }
    }
}

而API接口是:

@Multipart
@POST("Uploads/image/upload")
Call<UploadResponse> uploadImage(@Part MultipartBody.Part file,
                                             @Part("description") RequestBody description,
                                             @Query("access_token") String token);

此外,您还可以将这些代码转换为Kotlin等效代码。

相关问题