使用OKhttp3

时间:2019-04-28 18:20:20

标签: php android okhttp3

我正在使用OKhttp3进行网络请求。尝试将图像上传到服务器。这是我尝试过的方法,但是没有用。我在做什么错了?

public void upload(String url, String filePath) throws java.io.IOException {
        java.io.File file = new File(filePath);
        okhttp3.OkHttpClient client = new okhttp3.OkHttpClient(); 
        okhttp3.RequestBody formBody = new okhttp3.MultipartBody.Builder()
            .setType(okhttp3.MultipartBody.FORM)
            .addFormDataPart("file", file.getName(),
                             okhttp3.RequestBody.create(okhttp3.MediaType.parse("text/plain"), file))
            .addFormDataPart("other_field", "other_field_value")
            .build();
        okhttp3.Request request = new okhttp3.Request.Builder().url(url).post(formBody).build();
        okhttp3.Response response = client.newCall(request).execute();
    }

这是我的php代码:

<?php

    $uploaddir = '/uploads/';
    $uploadfile = $uploaddir . basename($_FILES['file']['name']);

    echo "<p>";

    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
      echo "File is valid, and was successfully uploaded.\n";
    } else {
       echo "Upload failed";
    }

    echo "</p>";
    echo '<pre>';
    echo 'Here is some more debugging info:';
    print_r($_FILES);
    print "</pre>";

    ?>

0 个答案:

没有答案