-1

I am trying to upload a video on the server , the video gets uploaded with the same size but when i open it it does not play

This is the code i am using to upload the file

package io.vov.bethattv;
/**
 * Created by conduit pc on 2/15/2017.
 */

public class Upload {

    //public static final String UPLOAD_URL = "http://192.168.113.2:8080/upload.php";
    public static final String UPLOAD_URL = "http://test.conduitsolutions.in/google_login/api/upload_file.php";
    private int serverResponseCode;


    public String uploadVideo(String file, String google_id) {

        String google_user_id = google_id;
//        String imageName = picturePath;
        String fileName = file;
        HttpURLConnection conn = null;
        String videoData;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1024 * 1024;
//        assert picturePath!=null;
//        File imageSource = new File(picturePath);
//        if(!imageSource.isFile()){
//            Log.e("HUZZA","Image File Does nt Exist");
//            return null;
//        }

        assert file!=null;
        File sourceFile = new File(file);
        if (!sourceFile.isFile()) {
            Log.e("Huzza", "Source File Does not exist");
            return null;
        }

        try {
            String title = "Video";
            String description = "simple video ";
            google_user_id = "KB";

//            String pic_ext = picturePath.substring(picturePath.lastIndexOf("."));
            String video_ext = file.substring(file.lastIndexOf("."));

//            FileInputStream imageInputSream = new FileInputStream(imageSource);
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(UPLOAD_URL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");

            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);


            dos = new DataOutputStream(conn.getOutputStream());
/*
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(uploadActivity);
            String id = prefs.getString("Id",null);*/



            dos.writeBytes("Content-Disposition: form-data; name=\"txttitle\""+ lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(title);
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + lineEnd);


            dos.writeBytes("Content-Disposition: form-data; name=\"txtdescription\""+ lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(description);
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + lineEnd);

            dos.writeBytes("Content-Disposition: form-data; name=\"txttitle\""+ lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(title);
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + lineEnd);


            dos.writeBytes("Content-Disposition: form-data; name=\"google_id\""+ lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(google_user_id);
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + lineEnd);


            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"videoFile");
            dos.writeBytes(video_ext + lineEnd);
          //dos.writeBytes("Content-Type: application/octet-stream\r\r\n");
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + lineEnd);


            bytesAvailable = fileInputStream.available();
            byte[] videoDATA = new byte[fileInputStream.available()];
            Log.i("Huzza", "Initial .available : " + bytesAvailable);
            byte[] base64 = Base64.encode(videoDATA,Base64.DEFAULT);


            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                dos.write(base64);

            }

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



//            dos.writeBytes(twoHyphens + boundary + lineEnd);
//            dos.writeBytes("Content-Disposition: form-data; name=\"image_file\"; filename=\"image_file");
//            dos.writeBytes(pic_ext+lineEnd);
//            //dos.writeBytes("Content-Disposition: form-data; name=\"image_file\"; filename=\"image_file\"\r\n");
//            dos.writeBytes(lineEnd);
//            dos.writeBytes(twoHyphens + boundary + lineEnd);


//            bytesAvailable = imageInputSream.available();
//            Log.i("Huzza", "Image .available : " + bytesAvailable);

//            bufferSize = Math.min(bytesAvailable, maxBufferSize);
//            buffer = new byte[bufferSize];
//
//            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
//
//            while (bytesRead > 0) {
//                dos.write(buffer, 0, bufferSize);
//                bytesAvailable = fileInputStream.available();
//                bufferSize = Math.min(bytesAvailable, maxBufferSize);
//                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
//            }
//            dos.writeBytes(lineEnd);
//            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            serverResponseCode = conn.getResponseCode();

            String res = conn.getResponseMessage();
            Log.e("Response>>>",res);

            fileInputStream.close();
            dos.flush();
            dos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (serverResponseCode == 200) {
            StringBuilder sb = new StringBuilder();
            try {
                assert conn != null;
                BufferedReader rd = new BufferedReader(new InputStreamReader(conn
                        .getInputStream()));
                String line;
                while ((line = rd.readLine()) != null) {
                    sb.append(line);
                }
                Log.e("Request >>>",sb.toString() );
                rd.close();
            } catch (IOException ioex) {
            }
            return sb.toString();
        } else {
            return "Could not upload";
        }

    }
}

The video file is uploading on the server database but when i download it and play it on the pc it does not play , similar problem with the Image . Any help is most appriciated.

This is My Upload Activity class where i get the path of the chosen image and pass it to Upload.java

package io.vov.bethattv;

public class UploadActivity extends AppCompatActivity implements View.OnClickListener {
    Button b1, b2, b3, b4;
    TextView textView, textViewResponse, imageTv, ImageResponseTV;
    private static final int SELECT_VIDEO = 3;
    private static final int SELECT_IMAGE = 4;
    public static final int MY_PERMISSIONS_READ = 123;
    public static final String UPLOAD_URL = "http://test.conduitsolutions.in/google_login/api/upload_file.php";
    String google_id;
    private String selectedPath, selectedImage, picturePath;
    Context ctx;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);
        b1 = (Button) findViewById(R.id.upload);
        b2 = (Button) findViewById(R.id.choose);
        b3 = (Button) findViewById(R.id.chooseImage);
        b4 = (Button) findViewById(R.id.uploadImage);
        textView = (TextView) findViewById(R.id.filePath);
        imageTv = (TextView) findViewById(R.id.imagePath);
        ImageResponseTV = (TextView) findViewById(R.id.serverResponseImage);
        textViewResponse = (TextView) findViewById(R.id.serverResponse);

        b1.setOnClickListener(this);
        b2.setOnClickListener(this);
        b3.setOnClickListener(this);
        b4.setOnClickListener(this);
        ctx = this;

        Intent i = getIntent();
        if (i.hasExtra("ID")) {
            google_id = i.getStringExtra("ID");
            Toast.makeText(UploadActivity.this, google_id, Toast.LENGTH_LONG).show();
        }

    }

    public void chooseVideo() {
        Intent i = new Intent();
        i.setType("video/*");
        i.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(i, "select video"), SELECT_VIDEO);

    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_VIDEO) {
                System.out.println("SELECT_VIDEO");
                Uri selectedVideoUri = data.getData();
                selectedPath = getPath(selectedVideoUri);
                textView.setText(selectedPath);
            } else if (requestCode == SELECT_IMAGE && resultCode == RESULT_OK && null != data) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                picturePath = cursor.getString(columnIndex);
                cursor.close();
                imageTv.setText(picturePath);

                //decodeFile(picturePath);;
            }
        }
    }

    public String getPath(Uri uri) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        String document_id = cursor.getString(0);
        document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
        cursor.close();

        cursor = getContentResolver().query(
                android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
        cursor.moveToFirst();
        String path = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA));
        cursor.close();

        return path;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_READ: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    chooseVideo();
                } else {
                    Toast.makeText(this, "NO PERMISSION GRANTED", Toast.LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

    public void uploadVideo() {
        class UploadVideo extends AsyncTask<Void, Void, String> {

            ProgressDialog uploading;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                //uploading.show();
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                //uploading.dismiss();
                textViewResponse.setText(Html.fromHtml("<b>Uploaded at <a href='" + s + "'>" + s + "</a></b>"));
                textViewResponse.setMovementMethod(LinkMovementMethod.getInstance());

            }

            @Override
            protected String doInBackground(Void... params) {

                Upload u = new Upload();
                String msg = u.uploadVideo(selectedPath, google_id);
                return msg;
            }
        }
        UploadVideo uv = new UploadVideo();
        uv.execute();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.upload:
                uploadVideo();
                break;
            case R.id.choose:
                if (ContextCompat.checkSelfPermission(UploadActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(UploadActivity.this,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            MY_PERMISSIONS_READ);


                } else {
                    chooseVideo();
                }
                break;
            case R.id.chooseImage:
                chooseImage();
                Toast.makeText(UploadActivity.this, "CLiclked", Toast.LENGTH_LONG).show();
                break;
            case R.id.uploadImage:

                break;
        }

    }

    private void chooseImage() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_IMAGE);
    }
}
Maveňツ
  • 1
  • 12
  • 50
  • 89
Kaustubh Bhagwat
  • 2,773
  • 1
  • 14
  • 20

1 Answers1

1

You have to work like this

public void connectForMultipart() throws Exception {
    con = (HttpURLConnection) ( new URL(url)).openConnection();
    con.setRequestMethod("POST");
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setRequestProperty("Connection", "Keep-Alive");
    con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    con.connect();
    os = con.getOutputStream();
}

public void addFormPart(String paramName, String value) throws Exception {
    writeParamData(paramName, value);
}

public void addFilePart(String paramName, String fileName, byte[] data) throws Exception {
    os.write( (delimiter + boundary + "\r\n").getBytes());
    os.write( ("Content-Disposition: form-data; name=\"" + paramName +  "\"; filename=\"" + fileName + "\"\r\n"  ).getBytes());
    os.write( ("Content-Type: application/octet-stream\r\n"  ).getBytes());
    os.write( ("Content-Transfer-Encoding: binary\r\n"  ).getBytes());
    os.write("\r\n".getBytes());

    os.write(data);
    
    os.write("\r\n".getBytes());
}   
public void finishMultipart() throws Exception {
    os.write( (delimiter + boundary + delimiter + "\r\n").getBytes());
}

For getting response

httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);

BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

String sResponse;
while ((sResponse = reader.readLine()) != null) 
 {
     s = s.append(sResponse);
 }

 if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
 {
     return s.toString();
 }else
 {
     return "{\"status\":\"false\",\"message\":\"Some error occurred\"}";
 }   
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

In place of video you can send anything(in your case its video file), you would like to... if it creates some heck then you should divide the large file into small parts then try to sending.And Join this small part on the server.

In my case httpmime-4.2.1-1.jar is only needed in this code

Community
  • 1
  • 1
Maveňツ
  • 1
  • 12
  • 50
  • 89