mvasco
mvasco

Reputation: 5101

PDF file not found in device´s content folder

I need to upload a file that is stored in the device on this folder:

/content:/com.android.providers.downloads.documents/document/7294

It is a PDF file, and I am not able to upload it using this code, as I do to upload other files like images or videos.

//android upload file to server
    public int uploadFile(final String selectedFilePath){



        int serverResponseCode = 0;

        HttpURLConnection connection;
        DataOutputStream dataOutputStream;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";


        int bytesRead,bytesAvailable,bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File selectedFile = new File(selectedFilePath);


        String[] parts = selectedFilePath.split("/");
        fileName = parts[parts.length-1];

        Log.d("ee", "Token login: selectedFilePath " + selectedFilePath);

        Log.d("ee", "Token login: fileName " + fileName);

        if (!selectedFile.isFile()){


            NuevoAnuncioOferta4PDF.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // nombreArchivo.setText("Foto no encontrada: " + selectedFilePath);
                }
            });
            return 0;
        }else{
            try{






                FileInputStream fileInputStream = new FileInputStream(selectedFile);
                URL url = new URL(SERVER_URL);
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);//Allow Inputs
                connection.setDoOutput(true);//Allow Outputs
                connection.setUseCaches(false);//Don't use a cached Copy
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setRequestProperty("ENCTYPE", "multipart/form-data");
                connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                connection.setRequestProperty("uploaded_file",selectedFilePath);


                //creating new dataoutputstream
                dataOutputStream = new DataOutputStream(connection.getOutputStream());

                //writing bytes to data outputstream
                dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
                dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";fileName=\""
                        + selectedFilePath + "\"" + lineEnd);

                dataOutputStream.writeBytes(lineEnd);

                //returns no. of bytes present in fileInputStream
                bytesAvailable = fileInputStream.available();
                //selecting the buffer size as minimum of available bytes or 1 MB
                bufferSize = Math.min(bytesAvailable,maxBufferSize);
                //setting the buffer as byte array of size of bufferSize
                buffer = new byte[bufferSize];

                //reads bytes from FileInputStream(from 0th index of buffer to buffersize)
                bytesRead = fileInputStream.read(buffer,0,bufferSize);

                //loop repeats till bytesRead = -1, i.e., no bytes are left to read
                while (bytesRead > 0){
                    //write the bytes read from inputstream
                    dataOutputStream.write(buffer,0,bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable,maxBufferSize);
                    bytesRead = fileInputStream.read(buffer,0,bufferSize);
                }

                dataOutputStream.writeBytes(lineEnd);
                dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                serverResponseCode = connection.getResponseCode();
                String serverResponseMessage = connection.getResponseMessage();

                Log.i("ee", "Server Response is foto subasta: " + serverResponseMessage + ": " + serverResponseCode);

                //response code of 200 indicates the server status OK
                if(serverResponseCode == 200){
                    NuevoAnuncioOferta4PDF.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //   nombreArchivo.setText("Foto subida con éxito");
                            // bUpload.setVisibility(View.GONE);
                            //enviar.setVisibility(View.VISIBLE);

                            //  Toast.makeText( NuevoVideoActivity.this,"Archivo subido "+fileName,Toast.LENGTH_SHORT).show();

                            Log.d("video subiendo"," video subiendo upload subido");




                            //editor2.putString("paciente_imagen_paciente", fileName);


                            //   editor2.apply();
                            Log.d("estoy en nuevo paciente","estoy en nuevo paciente 2 imagen_paciente "+fileName);






                        }
                    });
                }

                //closing the input and output streams
                fileInputStream.close();
                dataOutputStream.flush();
                dataOutputStream.close();
                dialog.dismiss();



            } catch (FileNotFoundException e) {
                e.printStackTrace();
                NuevoAnuncioOferta4PDF.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText( NuevoAnuncioOferta4PDF.this,"Foto no encontrada",Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (MalformedURLException e) {
                e.printStackTrace();
                Toast.makeText( NuevoAnuncioOferta4PDF.this, "Error de archivo", Toast.LENGTH_SHORT).show();

            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText( NuevoAnuncioOferta4PDF.this, "No se puede leer el archivo", Toast.LENGTH_SHORT).show();
            }


            return serverResponseCode;
        }


    }

I am not getting any exception or entry with any message in the logcat.

My question is: are PDF files to be managed in a different way that other files or is it a matter of the folder on the device? Images and videos are stored on other folders than content:

Upvotes: 0

Views: 525

Answers (1)

blackapps
blackapps

Reputation: 9282

Instead of opening a FileInputStream you open just an InputStream.

InputStream is = getContentResolver().openInputStream(data.getData()); 

The rest of the code is the same.

If you have a path to a file you can also use an InputStream:

InputStream is = new FileInputStream(file);

Upvotes: 1

Related Questions