duan47676379 2017-06-22 05:42
浏览 188

无法使用retrofit2将文件上传到服务器

I want to upload .pdf file to server where php code is

<?php

    $con = mysqli_connect("localhost","db_user","pwd","api_db");

        $user_id = $_POST['id'];
        $title = $_POST['cvTitle'];

        $allowedExts = array("docx","doc", "pdf", "txt");
    $temp = explode(".", $_FILES['cvfile']["name"]);
    $extension = end($temp);

    if ((($_FILES["cvfile"]["type"] == "application/pdf")
    || ($_FILES["cvfile"]["type"] == "application/text/plain")
    || ($_FILES["cvfile"]["type"] == "application/msword")
    || ($_FILES["cvfile"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
    && in_array($extension, $allowedExts)){

      //inner if
      if ($_FILES["cvfile"]["error"] > 0){
        echo "Failed 1";
      } else{

      }// end inner else

      $f_name = time().$_FILES['cvfile']["name"];

      move_uploaded_file($_FILES['cvfile']["tmp_name"],
      "upload/" . $f_name);

      $file_name = $f_name;


      } else {

          $json = array("File Type Not Allowed"); 

      header('content-type: application/json');
      echo json_encode($json);
      } // end else 

    $query = "UPDATE users set cv = '$file_name', cvTitle = '$title' where id = '$user_id'";

    if (mysqli_query($db,$query)) {

          $json = array("cv" => $file_name, "cvTitle" => $title); 

      header('content-type: application/json');
      echo json_encode($json);
      }

?>

my service is

@FormUrlEncoded
    @Multipart
    @POST("updatecv.php")
    Call<User> uploadUserCV(@Field("id") String id,
                            @Field("cvTitle") String cvTitle,
                            @Part MultipartBody.Part cv);

and finally I'm making call as

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_cv : {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("*/*");

                startActivityForResult(Intent.createChooser(intent, "Choose file using"), Constant.REQUEST_CODE_OPEN);
                return true;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        try {
            if (requestCode == Constant.REQUEST_CODE_OPEN){
                if (resultCode == RESULT_OK && null != data){
                    String type = Utils.getMimeType(UpdateProfileActivity.this, data.getData());
                    if (validateFileType(type)){
                        // Get the Image from data
                        Uri selectedFile = data.getData();
                        String[] filePathColumn = {MediaStore.Files.FileColumns.DATA};

                        Cursor cursor = getContentResolver().query(selectedFile, filePathColumn, null, null, null);
                        assert cursor != null;
                        cursor.moveToFirst();

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

                        uploadFile();

                    } else {
                        Toast.makeText(UpdateProfileActivity.this, "File type is not allowed", Toast.LENGTH_SHORT).show();
                    }
                    Log.e("FILE_TYPE", Utils.getMimeType(UpdateProfileActivity.this, data.getData()));
                }
            }

        } catch (Exception e){
            e.printStackTrace();
        }

    }

    // Uploading CV
    private void uploadFile() {
        final Dialog dialog = Utils.showPreloaderDialog(UpdateProfileActivity.this);
        dialog.show();
        // Map is used to multipart the file using okhttp3.RequestBody
        File file = new File(mediaPath);

        // Parsing any Media type file
        final RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
        MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);

        mUserCall = mRestManager.getApiService().uploadUserCV(uid, file.getName(), fileToUpload);
        mUserCall.enqueue(new Callback<User>() {


            @Override
            public void onResponse(Call<User> call, Response<User> response) {

                User user = response.body();

                Log.e("UPLOADED_FILE", "name is " + user.getCvTitle());

                dialog.dismiss();
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                dialog.dismiss();
                Log.e("UPLOADED_FILE_ERROR", "Message is " + t.getMessage());
                Toast.makeText(UpdateProfileActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
            }
        });

    }

    private boolean validateFileType(String type){
        String [] allowedFileTypes = {"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                                        "application/msword", "text/plain", "application/pdf"};
        for (int i = 0; i<=allowedFileTypes.length; i++){
            if (allowedFileTypes[i].equals(type)){
                return true;
            }
        }

        return false;
    }

but this code is not uploading the file to server no any errors. I wan to know where are the things wrong in php code or in android side. Any help is highly appreciated.

  • 写回答

2条回答 默认 最新

  • dtutlamjasblef7982 2017-06-22 05:51
    关注

    It seems you are testing on localhost then inside app localhost url is needed ....to grab that type ipconfig (in cmd on windows) copy that ip which is connected to lan or wifi. then check is upload.php file present or not on that ip address. for eg : 192.168.1.102/upload.php after that copy the ip and add in base url of retrofit builder in retrofit client class. Hope it will solve your issue :)

    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算