从DCIM文件夹上传图像

时间:2018-02-24 18:56:24

标签: android

我正在尝试通过Android设备上传图片,我尝试从大多数设备上传图片,图片已经从sdcard和DCIM文件夹上传,我的问题仅存在于三星设备中,现在非常特定于DCIM文件夹图像,如果我尝试从SD卡中的其他文件夹上传图像。

任何指针都会很棒,下面是代码片段:

public class   UploadImageService extends Service {

    private static final String TAG = UploadImageService.class.getSimpleName();
    private int mServerResponseCode = 0;
    private String upLoadServerUri = null;
    private Boolean mUsSuccess = true;
    private String mUploadImagePaths = "";
    private static RotiSharedPreferance sharedPref;

    @Override
    public void onCreate() {
        Log.d(TAG, "Service onCreate");
        sharedPref = new RotiSharedPreferance(RotiApplication.getInstance());

        //  upLoadServerUri = "http://mymasterpeice.byethost15.com/mobile/D21/upload_image.php";
        upLoadServerUri = Constants.ROTI_HOST_NAME + Constants.ROTI_IMAGE_UPLOAD_API;



    }



    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "Service onStartCommand " + startId);
        final int currentId = startId;
        Runnable r = new Runnable() {
            public void run() {
                File[] files = getFiles();
                for (int i = 0; i < files.length; i++) {
                    synchronized (this) {
                        try {
                            Log.d("MyService", "run (line 62): uploadFile " + files[i].getAbsolutePath());
                            uploadFile(files[i].getAbsolutePath());
                        } catch (Exception e) {
                            mUsSuccess = false;
                        }
                    }
                    Log.d(TAG, "Service running " + currentId);
                }
                stopSelf();
                Intent broadcastIntent = new Intent();
                broadcastIntent.setAction(Constants.UPDATE_UI_IMAGE_UPLOAD_ACK_BROADCAST);
                broadcastIntent.putExtra(Constants.UPDATE_UI_IMAGE_UPLOAD_ACK_BROADCAST_PARAM, mUploadImagePaths);
                sendBroadcast(broadcastIntent);
            }
        };
        Thread t = new Thread(r);
        t.start();
        return Service.START_STICKY;
    }

    public static File[] getFiles() {
        File mFile = null;
        File[] mListFile = null;
        try {
            // Locate the image folder in your SD Card
            mFile = new File(sharedPref.getString(Constants.UPLOAD_IMAGE_SHARED_PREF));
            mListFile = new File[1];
            mListFile[0] = mFile;
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        return mListFile;
    }


    @Override
    public IBinder onBind(Intent arg0) {
        Log.d(TAG, "Service onBind");
        return null;
    }

    /**
     * @inheritDoc
     */
    @Override
    public void onDestroy() {
        Log.d(TAG, "Service onDestroy");
    }


    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(fileName);
        if (!sourceFile.isFile()) {
            return 0;
        } else {
            try {
                // open a URL connection to the Servlet
                FileInputStream fileInputStream = new FileInputStream(
                        sourceFile);
                URL url = new URL(upLoadServerUri);
                // 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("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                        + sharedPref.getString(Constants.UPLOAD_IMAGE_NAME_SHARED_PREF) + "\"" + 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)
                mServerResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();
                StringBuilder result = new StringBuilder();
                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    InputStream in = new BufferedInputStream(conn.getInputStream());
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }
                }
                Log.d("uploadFile", "HTTP Response is : "
                        + serverResponseMessage + ": " + mServerResponseCode);
                Log.d("uploadFile", "HTTP Response is : " + result);
                JSONObject object = new JSONObject(String.valueOf(result));
                String filePath = (String) object.get("file_path");
                Log.d(TAG, "filepath : " + filePath);
                mUploadImagePaths = (filePath);
                if (mServerResponseCode != 200) {
                    mUsSuccess = false;
                }
                // close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();

            } catch (MalformedURLException ex) {
                mUsSuccess = false;
                ex.printStackTrace();
                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
                mUploadImagePaths = "";
            } catch (Exception e) {
                mUsSuccess = false;
                e.printStackTrace();
                Log.e(TAG, "Exception : " + e.getMessage(), e);
                mUploadImagePaths = ("");
            }
            return mServerResponseCode;
        } // End else block
    }
}

0 个答案:

没有答案