【问题标题】:could not be able to upload file to server using retrofit2无法使用改造 2 将文件上传到服务器
【发布时间】:2017-11-25 05:44:31
【问题描述】:

我想上传.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);
      }

?>

我的服务是

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

最后我打电话给

@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;
    }

但是这段代码没有将文件上传到服务器,没有任何错误。我想知道 php 代码或 android 端的问题在哪里。 非常感谢任何帮助。

【问题讨论】:

  • 你可以try this。这仅供您参考,它工作正常。

标签: php android retrofit retrofit2


【解决方案1】:

看来您正在本地主机上进行测试,然后需要在应用程序本地主机 url 内......来获取它 输入 ipconfig(在 Windows 上的 cmd 中) 复制连接到局域网或wifi的IP。 然后检查该IP地址上是否存在upload.php文件。 例如:192.168.1.102/upload.php 之后复制ip和 在改造客户端类中添加改造构建器的基本 url。 希望它能解决你的问题:)

【讨论】:

  • 感谢您的建议,但我正在使用远程服务器而不是本地主机测试的文件,.php 在那里也可用,但代码不起作用,请提供任何其他解决此问题的建议。
【解决方案2】:

根据您的 PHP,您正在寻找名称为 cvfile 的表单数据部分,但在 Android 代码中,您将 file 作为表单数据部分的名称传递。因此,您只需将file 更改为cvfile,如下所示:

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

希望它应该工作。

【讨论】:

    猜你喜欢
    • 2020-04-04
    • 2018-10-10
    • 2018-01-23
    • 2021-07-21
    • 2021-09-01
    • 2013-12-28
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多