保存到外部数据库

保存到外部数据库

我正在构建一个拍摄照片的相机应用程序并将其保存到外部数据库。当前代码适用于SD卡,但我不想使用SD卡。谁能告诉我如何使此代码保存到外部数据库。任何帮助将不胜感激。

我认为这部分:

//make picture and save to a folder
    private static File getOutputMediaFile() {
        //make a new file directory inside the "sdcard" folder
        File mediaStorageDir = new File("/sdcard/", "JCG Camera");

        //if this "JCGCamera folder does not exist
        if (!mediaStorageDir.exists()) {
            //if you cannot make this folder return
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }


是我可能必须改变的地方。我可能完全错了。我是新来的,所以请原谅我。我在这里先向您的帮助表示感谢。

我的课:

public class AndroidCameraExample extends Activity {
    private Camera mCamera;
    private CameraPreview mPreview;
    private PictureCallback mPicture;
    private Button capture, switchCamera;
    private Context myContext;
    private LinearLayout cameraPreview;
    private boolean cameraFront = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        myContext = this;
        initialize();
    }

    private int findFrontFacingCamera() {
        int cameraId = -1;
        // Search for the front facing camera
        int numberOfCameras = Camera.getNumberOfCameras();
        for (int i = 0; i < numberOfCameras; i++) {
            CameraInfo info = new CameraInfo();
            Camera.getCameraInfo(i, info);
            if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
                cameraId = i;
                cameraFront = true;
                break;
            }
        }
        return cameraId;
    }

    private int findBackFacingCamera() {
        int cameraId = -1;
        //Search for the back facing camera
        //get the number of cameras
        int numberOfCameras = Camera.getNumberOfCameras();
        //for every camera check
        for (int i = 0; i < numberOfCameras; i++) {
            CameraInfo info = new CameraInfo();
            Camera.getCameraInfo(i, info);
            if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
                cameraId = i;
                cameraFront = false;
                break;
            }
        }
        return cameraId;
    }

    public void onResume() {
        super.onResume();
        if (!hasCamera(myContext)) {
            Toast toast = Toast.makeText(myContext, "Sorry, your phone does not have a camera!", Toast.LENGTH_LONG);
            toast.show();
            finish();
        }
        if (mCamera == null) {
            //if the front facing camera does not exist
            if (findFrontFacingCamera() < 0) {
                Toast.makeText(this, "No front facing camera found.", Toast.LENGTH_LONG).show();
                switchCamera.setVisibility(View.GONE);
            }
            mCamera = Camera.open(findBackFacingCamera());
            mPicture = getPictureCallback();
            mPreview.refreshCamera(mCamera);
        }
    }

    public void initialize() {
        cameraPreview = (LinearLayout) findViewById(R.id.camera_preview);
        mPreview = new CameraPreview(myContext, mCamera);
        cameraPreview.addView(mPreview);

        capture = (Button) findViewById(R.id.button_capture);
        capture.setOnClickListener(captrureListener);

        switchCamera = (Button) findViewById(R.id.button_ChangeCamera);
        switchCamera.setOnClickListener(switchCameraListener);
    }

    OnClickListener switchCameraListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            //get the number of cameras
            int camerasNumber = Camera.getNumberOfCameras();
            if (camerasNumber > 1) {
                //release the old camera instance
                //switch camera, from the front and the back and vice versa

                releaseCamera();
                chooseCamera();
            } else {
                Toast toast = Toast.makeText(myContext, "Sorry, your phone has only one camera!", Toast.LENGTH_LONG);
                toast.show();
            }
        }
    };

    public void chooseCamera() {
        //if the camera preview is the front
        if (cameraFront) {
            int cameraId = findBackFacingCamera();
            if (cameraId >= 0) {
                //open the backFacingCamera
                //set a picture callback
                //refresh the preview

                mCamera = Camera.open(cameraId);
                mPicture = getPictureCallback();
                mPreview.refreshCamera(mCamera);
            }
        } else {
            int cameraId = findFrontFacingCamera();
            if (cameraId >= 0) {
                //open the backFacingCamera
                //set a picture callback
                //refresh the preview

                mCamera = Camera.open(cameraId);
                mPicture = getPictureCallback();
                mPreview.refreshCamera(mCamera);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //when on Pause, release camera in order to be used from other applications
        releaseCamera();
    }

    private boolean hasCamera(Context context) {
        //check if the device has camera
        if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            return true;
        } else {
            return false;
        }
    }

    private PictureCallback getPictureCallback() {
        PictureCallback picture = new PictureCallback() {

            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                //make a new picture file
                File pictureFile = getOutputMediaFile();

                if (pictureFile == null) {
                    return;
                `enter code here`}
                try {
                    //write the file
                    FileOutputStream fos = new FileOutputStream(pictureFile);
                    fos.write(data);
                    fos.close();
                    Toast toast = Toast.makeText(myContext, "Picture saved: " + pictureFile.getName(), Toast.LENGTH_LONG);
                    toast.show();

                } catch (FileNotFoundException e) {
                } catch (IOException e) {
                }

                //refresh camera to continue preview
                mPreview.refreshCamera(mCamera);
            }
        };
        return picture;
    }

    OnClickListener captrureListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            mCamera.takePicture(null, null, mPicture);
        }
    };

    //make picture and save to a folder
    private static File getOutputMediaFile() {
        //make a new file directory inside the "sdcard" folder
        File mediaStorageDir = new File("/sdcard/", "JCG Camera");

        //if this "JCGCamera folder does not exist
        if (!mediaStorageDir.exists()) {
            //if you cannot make this folder return
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }

        //take the current timeStamp
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        //and make a media file:
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");

        return mediaFile;
    }

    private void releaseCamera() {
        // stop and release camera
        if (mCamera != null) {
            mCamera.release();
            mCamera = null;
        }
    }
}

最佳答案

public int uploadFile(String sourceFileUri) {

                 String fileName = sourceFileUri;

                 HttpURLConnection conn = null;
                 DataOutputStream dos = null;
                 String lineEnd = "\r\n";
                 String twoHyphens = "--";
                 String boundary = "*****";
                 int bytesRead, bytesAvailable, bufferSize;
                 byte[] buffer;
                 int maxBufferSize = 1 * 1024 * 1024;
                 File sourceFile = new File(sourceFileUri);

                 if (!sourceFile.isFile()) {
                      runOnUiThread(new Runnable() {
                          @Override
                        public void run() {
                             Toast.makeText(getBaseContext(), "Source File not exist :"+imagepath, Toast.LENGTH_LONG).show();
                          }
                      });
                      return 0;
                 }
                 else
                 {
                      try {

                            // open a URL connection to the Servlet
                          FileInputStream fileInputStream = new FileInputStream(sourceFile);
                          String where = "SERVER_ADDRESS";
                          URL url = new URL(where);

                          // Open a HTTP  connection to  the URL
                          conn = (HttpURLConnection) url.openConnection();
                          conn.setDoInput(true); // Allow Inputs
                          conn.setDoOutput(true); // Allow Outputs
                          conn.setUseCaches(false); // Don't use a Cached Copy
                          conn.setRequestMethod("POST");
                          conn.setRequestProperty("Connection", "Keep-Alive");
                          conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                          conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                          conn.setRequestProperty("uploaded_file", fileName);

                          dos = new DataOutputStream(conn.getOutputStream());

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

                          dos.writeBytes(lineEnd);

                          // create a buffer of  maximum size
                          bytesAvailable = fileInputStream.available();

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

                          // read file and write it into form...
                          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);

                           }

                          // send multipart form data necesssary after file data...
                          dos.writeBytes(lineEnd);
                          dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                          // Responses from the server (code and message)
                          serverResponseCode = conn.getResponseCode();
                          final String serverResponseMessage = conn.getResponseMessage();

                          Log.i("uploadFile", "HTTP Response is : "
                                  + serverResponseMessage + ": " + serverResponseCode);

                          if(serverResponseCode == 200){

                              runOnUiThread(new Runnable() {
                                   @Override
                                public void run() {

                                       String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                             +"SERVER ADDRESS";
                                   }
                               });
                          }

                          //close the streams //
                          fileInputStream.close();
                          dos.flush();
                          dos.close();

                     } catch (MalformedURLException ex) {

                         //dialog.dismiss();
                         ex.printStackTrace();

                         runOnUiThread(new Runnable() {
                             @Override
                            public void run() {
                                 Toast.makeText(CLASS_NAME.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                             }
                         });

                         Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
                     } catch (Exception e) {

                         //dialog.dismiss();
                         e.printStackTrace();

                         runOnUiThread(new Runnable() {
                             @Override
                            public void run() {
                                 Toast.makeText(CLASS_NAME.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
                             }
                         });
                         Log.e("Upload file to server Exception", "Exception : "  + e.getMessage(), e);
                     }
                    // dialog.dismiss();
                     return serverResponseCode;

                  } // End else


将Server_Address更改为预期的url,将Class_Name更改为使用代码的类。
用图像路径调用函数

uploadFile(imagepath);


服务器代码是这样的:

<?php

   $file_path = "uploads/";

   $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    echo $_FILES['uploaded_file']['name'];
   if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
       echo "success";
   } else{
       echo "fail";
   }

?>

10-08 16:07