无法在 Android 中上传文件并且没有错误的详细信息

Unable to upload a file in Android and there's no details of an error

我正在尝试上传 Android/Kotlin 中的文件:

class MainActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    //...........

    UploadFilesTask().execute(1)

}

//.......

private class UploadFilesTask : AsyncTask<Int, Int, Int>() {
    override fun doInBackground(vararg params: Int?): Int? {
      val MEDIA_TYPE_PNG = MediaType.parse("image/jpg")
      val client = OkHttpClient()
      val requestBody = MultipartBody.Builder()
          .setType(MultipartBody.FORM)
          .addFormDataPart("title", "test123")
          .addFormDataPart("file", "image-name-123.jpg", RequestBody.create(MEDIA_TYPE_PNG,
              File("/storage/emulated/0/Download/real-file-name.jpg")))
          .build()

      val request = Request.Builder()
          .url("http://httpbin.org/post")
          .post(requestBody)
          .build()

      val response = client.newCall(request).execute()
      if (!response.isSuccessful) {
        throw IOException("Unexpected code " + response)
      } else {
        Log.d("test", "Done123")
        Log.d("test", response.body().string())
      }

      return 123
    }

    protected fun onProgressUpdate(vararg progress: Int) {
    }

    protected override fun onPostExecute(result: Int?) {
    }
  }

我在 运行 时看到的唯一错误消息是:

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1

我该如何解决?

已设置权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />

和依赖项:

compile "com.squareup.okhttp3:okhttp:3.0.1"

我测试了你的代码,它按预期工作。与我的唯一区别是我使用的是真实设备,所以我的文件路径是/storage/sdcard0/Download/real-file-name.jpg。我建议您检查模拟器存储中是否存在该文件:

adb shell ls /storage/emulated/0/Download/real-file-name.jpg

输出应该是这样的:

-rw-rw-r-- root sdcard_rw 21577 2016-01-26 16:16 real-file-name.jpg

这是您的代码的输出示例

01-26 18:00:52.877 29568-29644/com.omainegra.sof D/test: Done123
01-26 18:00:54.383 29568-29644/com.omainegra.sof D/test: {
                                                         "args": {}, 
                                                         "data": "", 
                                                         "files": {
                                                             "file": "data:image/jpg;base64,/9j/4AAQSkZJRgAB...

Recomendation

使用 RxAndroid

可以轻松完成更好的(反应性方法)
class MainActivity : AppCompatActivity() {

    val observable = Observable.create<String> { observer ->
        try {
            if (!observer.isUnsubscribed) {
                val MEDIA_TYPE_PNG = MediaType.parse("image/jpg")
                val client = OkHttpClient()
                val requestBody = MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("title", "test123")
                        .addFormDataPart("file", "image-name-123.jpg", RequestBody.create(MEDIA_TYPE_PNG,
                                File("/storage/sdcard0/Download/real-file-name.jpg")))
                        .build()

                val request = Request.Builder()
                        .url("http://httpbin.org/post")
                        .post(requestBody)
                        .build()

                val response = client.newCall(request).execute();

                if (!response.isSuccessful)
                    throw IOException("Unexpected code " + response);

                observer.onNext(response.body().string())
            }
        } catch (e: Exception) {
            observer.onError(e);
        }
    }

    lateinit var subscription: Subscription

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        subscription = observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ response ->
                    Log.d("test", "Done123")
                    Log.d("test", response)
                }, { error ->
                    Log.e("test", "onError", error)
                })
    }

    override fun onDestroy(){
        super.onDestroy()
        subscription.unsubscribe()
    }
}

将依赖项添加到您的 build.gradle

compile 'io.reactivex:rxjava:1.1.0'
compile 'io.reactivex:rxandroid:1.1.0'