java - 将图像保存到外部数据库服务器

标签 java android camera

我正在构建一个相机应用程序,该应用程序可以拍摄照片并将其保存到外部数据库。当前代码适用于 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;
            }
        }

是我可能需要更改的地方。不过我可能完全错了。我对此很陌生,请原谅我。提前感谢您的帮助。

我的类(class):

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"; 
   }

?>

关于java - 将图像保存到外部数据库服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29708251/

相关文章:

android - 在 Kotlin 中使用 @Parcelize 注释时如何忽略字段

android - react native : Can't show remote images in release mode on android device

java - 如何将相同的方法添加到多个类( Activity )

android - 你如何限制 Intent 选择器只显示特定的应用程序?

java - 我们是否应该在 kubernetes 容器中设置 -Xmx(最大 Java 堆大小)

java - JFreechart 循环遍历极坐标图扇区

java - 从自定义序列化程序访问字段注释

java - String.contain 在波斯字符串的对象序列化中

python - 如何构建包含cv模块的exe文件

android - android中的光测量