使用Retrofit 2将Pdf上传到服务器

时间:2017-07-27 08:36:45

标签: php android retrofit2

我正在尝试使用 Retrofit 2.0 将Pdf文件上传到服务器,并将其路径存储到我的MySQL数据库中。我成功地存储了路径,但是应该存储在我的主目录中的pdf已损坏。

upload.php的

<?php

require "init.php";

if($con)
{
    $title=$_POST['title'];
    $pdf=$_POST['pdf'];

    //Getting the server ip
    $server_ip = gethostbyname(gethostname());

    $upload_path="uploads/$title.pdf";

    $upload_url = 'http://'.$server_ip.'/pdfupload1/'.$upload_path;

    $sql="insert into pdfinfo1(title,path) values('$title','$upload_url');";

        if(mysqli_query($con,$sql))
        {
            file_put_contents($upload_path,$pdf);

            echo json_encode(array('response'=>"Pdf Uploaded Successfully"));

        }
        else
        {
            echo json_encode(array('response'=>"Pdf Upload Failed"));

        }
        mysqli_close($con);
}
?>

ApiClient.java

    public class ApiClient
{

    private static final String BaseUrl="http://10.0.2.2/pdfupload1/";

    private static Retrofit retrofit;

    public static Retrofit getApiClient()
    {
        if(retrofit==null)
        {
            retrofit=new Retrofit.Builder().baseUrl(BaseUrl).addConverterFactory(GsonConverterFactory.create()).build();
        }
        return retrofit;
    }
}

ApiInterface.java

    public interface ApiInterface
{
    @Multipart
    @POST("upload.php")
    Call<PdfClass> PdfUploadFunction (@Part("title") RequestBody title, @Part("pdf") RequestBody image);
}

PdfClass.java

   public class PdfClass
{
    //This is a Model Class Retrofit

    @SerializedName("title")
    private String Title;

    @SerializedName("pdf")
    private String Pdf;

    @SerializedName("response")
    private String Response;

    public String getResponse() {
        return Response;
    }
}

FilePath.java

   public class FilePath {

    /**
     * Method for return file path of Gallery image
     *
     * @param context
     * @param uri
     * @return path of the selected image file from gallery
     */

    public static String getPath(final Context context, final Uri uri)
    {
        //check here to KITKAT or new version
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {

            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }

            //DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }

            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] {
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}

FirstActivity.java

  public class FirstActivity extends AppCompatActivity {
    Button button1,button2;
    EditText imagename;
    ImageView imageView;
    private static final int PDF_REQUEST=777;
    private Bitmap bitmap;

    public int PDF_REQ_CODE = 1;

    String PdfNameHolder, PdfPathHolder, PdfID;
    Uri uri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);

        button1=(Button)findViewById(R.id.button);
        button2=(Button)findViewById(R.id.button2);

        imagename=(EditText)findViewById(R.id.editText1);
        //imageView=(ImageViewfindViewById(R.id.imageView1);




        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //selectImage();
                selectPdf();


            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // uploadImage();
                PdfUploadFunction();

            }
        });

    }

    private void selectPdf()
    {
        Intent intent = new Intent();

        intent.setType("application/pdf");

        intent.setAction(Intent.ACTION_GET_CONTENT);

        startActivityForResult(Intent.createChooser(intent, "Select Pdf"), PDF_REQ_CODE);
    }

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

        if (requestCode == PDF_REQ_CODE && resultCode == RESULT_OK && data != null && data.getData() != null) {

            uri = data.getData();

        }
    }

    public void PdfUploadFunction() {

        PdfNameHolder = imagename.getText().toString();

        PdfPathHolder = FilePath.getPath(this, uri);

        //File file=new File(uri.getPath());




            RequestBody Title=RequestBody.create(MediaType.parse("text/plain"),imagename.getText().toString());
            RequestBody Pdf=RequestBody.create(MediaType.parse("application/pdf"), PdfPathHolder);
            ApiInterface apiInterface=ApiClient.getApiClient().create(ApiInterface.class);
            Call<PdfClass> call=apiInterface.PdfUploadFunction(Title,Pdf);

            call.enqueue(new Callback<PdfClass>() {
                @Override
                public void onResponse(Call<PdfClass> call, Response<PdfClass> response) {

                    PdfClass pdfClass=response.body();
                    Toast.makeText(getApplicationContext(),"Server Response: "+pdfClass.getResponse(),Toast.LENGTH_LONG).show();
                }

                @Override
                public void onFailure(Call<PdfClass> call, Throwable t) {

                }
            });

    }

    public void AllowRunTimePermission(){

        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE))
        {

            Toast.makeText(this,"READ_EXTERNAL_STORAGE permission Access Dialog", Toast.LENGTH_LONG).show();

        } else {

            ActivityCompat.requestPermissions(this,new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE}, 1);

        }
    }

    @Override
    public void onRequestPermissionsResult(int RC, String per[], int[] Result) {

        switch (RC) {

            case 1:

                if (Result.length > 0 && Result[0] == PackageManager.PERMISSION_GRANTED) {

                    Toast.makeText(this,"Permission Granted", Toast.LENGTH_LONG).show();

                } else {

                    Toast.makeText(this,"Permission Canceled", Toast.LENGTH_LONG).show();

                }
                break;
        }
    }
}

提前感谢您的帮助..

2 个答案:

答案 0 :(得分:2)

PdfUploadFunction()将文件附加到RequestBody pdf时,调用文件的路径而不是实际文件。

修改为

RequestBody Pdf=RequestBody.create(MediaType.parse("application/pdf"), new File(PdfPathHolder))
对于FilePath课程,

没有谢谢。 需要我的代码才能工作。

另请考虑在Retrofit getApiClient()中添加呼叫超时,因为根据文件大小,呼叫可能会导致TimeOut失败。

修改为

public static Retrofit getApiClient(){
    if(retrofit==null){
        retrofit=new Retrofit.Builder()
                .baseUrl(BaseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .client(new OkHttpClient().newBuilder()
                    .connectTimeout(20, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .build())
                .build();
    }
    return retrofit;
}

答案 1 :(得分:0)

有点晚了, 但我认为你 要做这样的改变

 String PDFPATH = FilePath.getPath(MainActivity.this,uri);
    File file = new File(PDFPATH);
    String namepdf = "newpdf";
    pdfname.setText(file.getName());


    RequestBody Title = RequestBody.create(MediaType.parse("text/plain"),namepdf);
    RequestBody PDFreq = RequestBody.create(MediaType.parse("application/pdf"),file.getName());
    //MultipartBody.Part PDF = MultipartBody.Part.createFormData("pdf",file.getName(),PDFreq);
    APIInterface apiInterface=ApiClient.getApiClient().create(APIInterface.class);
    Call<PdfClass> call=apiInterface.PdfUploadFunction(Title,PDFreq);

在PDFreq =添加file.getname()而不是新文件(pdfpath),它将显示在您的数据库pdf中,我们需要pdf路径并将其存储在我们的服务器中,因此 进行这个小的更改,您就可以开始了...