I'm writing programs to try to learn Android. I'm trying to get a video to upload to the server with retrofit. My retrofit works uploading EditText etc. I'm using the same IP address here as I do there.
In the code the camera works fine records video and renames the video, I believe the select video works fine (not totally sure on that but gallery opens I select a video and it doesn't crash, and the PHP allows me to post a video using Postman). But when I hit the upload button crash.
I'm not sure if the issue is in getting the real path, in the retrofit code, or maybe my file select doesn't work? I tried multiple examples. Just not getting it to work. I can't figure out the error. I tried to throw some toasts in there to see if I am getting an error but I don't ever get a toast.
Here is my code:
Slim/PHP index
$app->post('/saveFile', function(Request $request, Response $response){
$response = array();
if (isset($_POST['desc']) && ($_POST['ID']) && strlen($_POST['desc']) > 0 &&
$_FILES['image']['error'] === UPLOAD_ERR_OK) {
$upload = new uploads();
$file = $_FILES['image']['tmp_name'];
$desc = $_POST['desc'];
$ID = $_POST['ID'];
if ($upload->saveFile($ID, $file,
getFileExtension($_FILES['image']['name']), $desc)) {
$response['error'] = false;
$response['message'] = 'File Uploaded Successfullly';
}
else {
$response['error'] = true;
$response['message'] = 'Required parameters are not available';
}
echo json_encode($response);
}
});
function getFileExtension($file)
{
$path_parts = pathinfo($file);
return $path_parts['extension'];
}
uploads.php
class uploads
{
private $con;
public function __construct()
{
require_once dirname(__FILE__) . '/DbConnect.php';
$db = new DbConnect();
$this->con = $db->connect();
}
public function saveFile($ID, $file, $extension, $desc)
{
$name = round(microtime(true) * 1000) . '.' . $extension;
$filedest = dirname(__FILE__) . UPLOAD_PATH . $name;
move_uploaded_file($file, $filedest);
$url = $server_ip = gethostbyname(gethostname());
$stmt = $this->con->prepare("INSERT INTO images (ID, description, url)
VALUES (?, ?, ?)");
$stmt->bind_param("sss", $ID, $desc, $name);
if ($stmt->execute())
return true;
else
return false;
}
}
API interface
@Multipart
@POST("saveFile")
Call<MyResponse> uploadImage(@Part MultipartBody.Part file, @Part("desc")
RequestBody desc, @Field("ID") String ID);
my activity class
public class vidcam extends Activity implements View.OnClickListener {
String ID, prepend;
private final int VIDEO_REQUEST_CODE = 100;
private final int REQUEST_TAKE_GALLERY_VIDEO =22;
File video_file;
Button RecordButton, tobaitana, viduploadbutton, uploadvideo;
Uri selectedVideo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vidcam);
RecordButton = (Button) findViewById(R.id.RecordButton);
RecordButton.setOnClickListener(this);
tobaitana = (Button) findViewById(R.id.tobaitana);
tobaitana.setOnClickListener(this);
viduploadbutton = (Button) findViewById(R.id.viduploadbutton);
viduploadbutton.setOnClickListener(this);
uploadvideo = (Button) findViewById(R.id.uploadvideo);
uploadvideo.setOnClickListener(this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
if (requestCode == VIDEO_REQUEST_CODE){
Toast.makeText(getApplicationContext(), "Video Saved",
Toast.LENGTH_LONG).show();
}
if (resultCode == RESULT_OK) {
if(requestCode == REQUEST_TAKE_GALLERY_VIDEO){
selectedVideo = data.getData();
}}}
public File getfilepath () throws IOException {
File videofolder = new File("sdcard/video_app");
if (!videofolder.exists())
{
videofolder.mkdir();
}
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
prepend = "MOBILITY_" + timestamp + "_";
video_file = File.createTempFile(prepend, ".mp4", videofolder);
return video_file;
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.RecordButton:
Intent video_intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
File videolocation = null;
try {
videolocation = getfilepath();
} catch (IOException e) {
e.printStackTrace();
}
Uri video_uri = Uri.fromFile(videolocation);
video_intent.putExtra(MediaStore.EXTRA_OUTPUT, video_uri);
video_intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(video_intent, VIDEO_REQUEST_CODE);
break;
case R.id.tobaitana:
Intent toanbait = new Intent(this, Abait.class);
startActivity(toanbait);
break;
case R.id.viduploadbutton:
Intent selectfile = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(selectfile, REQUEST_TAKE_GALLERY_VIDEO);
break;
case R.id.uploadvideo:
uploadFile(selectedVideo);
break;
}
}
public void useID() {
SharedPreferences shareID = getSharedPreferences("shareID", Context.MODE_PRIVATE);
ID = shareID.getString("ID", "");
}
private String getRealPathFromURI(Uri contentUri) {
String filePath;
Cursor cursor = getContentResolver().query(contentUri, null, null, null, null);
if(cursor == null)
{
filePath = contentUri.getPath();
}else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Video.VideoColumns.DATA);
filePath = cursor.getString(idx);
cursor.close();
Toast.makeText(getApplicationContext(), "realpath toast" + filePath, Toast.LENGTH_LONG).show();
}
return filePath;
}
private void uploadFile(Uri selectedVideo) {
useID();
File vidfile = new File(getRealPathFromURI(selectedVideo));
if (vidfile.exists()) {
RequestBody requestBody = RequestBody.create(MediaType.parse(getContentResolver().getType(selectedVideo)), vidfile);
MultipartBody.Part file = MultipartBody.Part.createFormData("filename", vidfile.getName(), requestBody);
RequestBody desc = RequestBody.create(MediaType.parse("text/plain"), vidfile.getName());
Call<MyResponse> call = RetrofitClient.getInstance().getAPIService().uploadImage(file, desc, ID);
call.enqueue(new Callback<MyResponse>() {
@Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if (!response.body().error) {
Toast.makeText(getApplicationContext(), "File Uploaded Successfully...", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Some error occurred...", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<MyResponse> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
} else {Toast.makeText(getApplicationContext(), "no file exists...", Toast.LENGTH_LONG).show();
}
}
}