简体   繁体   English

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

[英]could not be able to upload file to server using retrofit2

I want to upload .pdf file to server where php code is 我想将.pdf文件上传到PHP代码所在的服务器

<?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. 我想知道php代码或android方面出了什么问题。 Any help is highly appreciated. 非常感谢您的帮助。

According to your PHP, you're looking for form-data part with name cvfile , but in Android code you're passing file as a name of the form-data part. 根据您的PHP,您正在寻找名称为cvfile表单数据部分,但是在Android代码中,您正在传递file作为表单数据部分的名称。 So all you need is to change file to cvfile , like this: 因此,您所需cvfile就是将file更改为cvfile ,如下所示:

MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("cvfile", file.getName(), requestBody);

Hopefully it should work. 希望它应该工作。

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. 看来您正在localhost上进行测试,然后在应用程序localhost内需要URL ....以获取ipconfig类型(在Windows的cmd中)复制连接到lan或wifi的ip。 then check is upload.php file present or not on that ip address. 然后检查该IP地址上是否存在upload.php文件。 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. 例如:192.168.1.102/upload.php,然后复制IP并在改造客户端类中添加改造生成器的基本URL。 Hope it will solve your issue :) 希望它能解决您的问题:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM