0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

OkHttp3のPost通信で画像のアップロード

Last updated at Posted at 2024-11-21

画像データ送信の覚書き
コピペでいけますように

環境設定

build.gradle.ks
    implementation("com.squareup.okhttp3:okhttp:4.9.1")
manifests
     <uses-permission
        android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        tools:ignore="ScopedStorage" />
    <uses-permission
        android:name="android.permission.READ_EXTERNAL_STORAGE"
        tools:ignore="ScopedStorage" />
<application
        android:usesCleartextTraffic="true"
>

権限許可

MainActivity

ActivityCompat.requestPermissions(
            this, arrayOf(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
            ), 1
        )

画像アップロードクラス

ImageUp.kt
import android.os.Handler
import android.os.Looper
import android.util.Log
import java.util.concurrent.TimeUnit
import okhttp3.OkHttpClient
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.Response
import java.io.File
import java.io.IOException
import java.lang.Exception
import java.nio.file.Files

class ImageUp {
    private var timeOut = "300000"
    private var readTime = "100000"
    private val client = OkHttpClient.Builder()
        .connectTimeout(timeOut.toLong(), TimeUnit.MILLISECONDS)
        .readTimeout(readTime.toLong(), TimeUnit.MILLISECONDS)
        .build()
        
    private val mainHandler = Handler(Looper.getMainLooper())
    
    fun startPostRequest(file: File, endProcess:(String)->Unit){
    var compMsg = "アップロード失敗"
        //送る画像ファイルの設定
        val mimeType: String = Files.probeContentType(file.toPath())
        val media = mimeType.toMediaTypeOrNull()
        val requestBody: RequestBody = MultipartBody.Builder().setType(MultipartBody.FORM)
            //File送信引数(name:String,filename: String?,body: RequestBody)
            .addFormDataPart("file", file.name,file.asRequestBody(media))
            //他一緒に送るものがあれば追加する
            //文字列引数(name:String,value: String)
            .addFormDataPart("ADD","value")
            .build()
        val request = Request.Builder()
            .url(url)//保存先URL
            .header("Connection", "close")
            .post(requestBody)
            .build()
        client.newCall(request).enqueue(object :Callback {
            override fun onFailure(call: Call, e: IOException) {
                Log.e("Error", e.toString())
                endProcess(compMsg)
            }
            override fun onResponse(call: Call, response: Response) {
                try {
                    val responseBody = response.body?.string().orEmpty()
                    Log.d("Response", responseBody)
                    if (response.code == 200) {
                        compMsg = "アップロード成功"
                    }
                } catch (e: Exception) {
                    Log.e("Error", e.toString())
                } finally {
                    mainHandler.post {
                        endProcess(compMsg)
                    }
                }
            }
        })
    }
}

File送信リクエスト

とりあえずデフォルトのMainActivityでリクエスト

MainActivity

override fun onStart() {
    super.onStart()
    ImageUpRequest()
}
private fun ImageUpRequest(){
    //内部ストレージのimage00.jpgファイルをアップロードしたい
     val screenFile = File(externalCacheDir, "image00.jpg")
     //このresultはImageUpの結果(endProcess:(String))を元に(res: String)としてメインスレッドに反映する
     val result = fun(res: String){
     if(res == "アップロード成功"){
                AlertDialog.Builder(this)
                    .setTitle(res)
                    .setMessage("送信出来ました")
                    .setPositiveButton("OK") { _, _ ->
                        //送信成功確認後の処理
                    }
                    .show()
            }else{
                AlertDialog.Builder(this)
                    .setTitle(res)
                    .setMessage("エラー発生")
                    .setPositiveButton("OK") { _, _ ->
                        //送信失敗確認後の処理
                    }
                    .show()
            }
     }
     //処理後に行ってほしいresult処理を ImageUp()に投げている
     ImageUp().startPostRequest(file,result)

}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?