如何在Android中上传少于1 MB的图像使用齐射库?

时间:2016-07-26 05:23:42

标签: android

我想检查不到1 MB的图片并使用Android中的排球库上传到远程服务器.....请帮帮我。

对于选择的图片,我使用以下代码:

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),PICK_IMAGE_REQUEST);

在活动结果中我使用:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            try {
                if (Build.VERSION.SDK_INT>19){
                }else {
                    Uri filePath = data.getData();
                    File file = new File(filePath.getPath());
                    int length = (int) file.length();
                    double lengthkb = length / 1024;
                    if (lengthkb > 0.0D) { 
                        lengthmb = lengthkb / 1024; 
                        Log.d("picsize", lengthmb + "");
                    } else {
                        File file2 = new File(getPath(filePath));
                        int length2 = (int) file2.length();
                        double lengthkb2 = length2 / 1024; 
                        lengthmb = lengthkb2 / 1024;
                        Log.d("picsize", lengthmb + ""); 
                    }
                    bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath); imageViewProfileImage.setImageBitmap(bitmap); }
            } catch(IOException e){
                e.printStackTrace(); 
            }
        }

    }

1 个答案:

答案 0 :(得分:1)

  • 从图库中选择图像后,该代码中的波纹管代码会传递参数和图像URL。

上传图片方法:

      private void uploadPatientReport() {
                dialog = ProgressDialog.show(getContext(), "", "Uploading file...", true);
                final Map<String, String> parameters = new HashMap<String, String>();
                parameters.put(Constant.ACTION, "reports");
                parameters.put(Constant.ROLE_ID, SafeUtils.getRoleID(getContext()));
                parameters.put(Constant.PATI_ID, SafeUtils.getUserID(getContext()));
                parameters.put(Constant.REPORT_DATE, "'"+SafeUtils.getCurrentDate(getContext())+"'");
                parameters.put(Constant.REP_TITLE, fileTitle);
                parameters.put(Constant.IMG_EXTENTION_STATUS, "");
                parameters.put(Constant.PATIENT_APPO_ID, patientAppointMentId);

                new Thread(new Runnable() {
                    public void run() {
                        runOnUiThread(new Runnable() {
                            public void run() {
                            }
                        });
                        int response = uploadFile(getPath(imagePathUri), parameters);
                        System.out.println("RES : " + response);
                    }
                }).start();

        }

 public String getPath(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String picturePath = cursor.getString(column_index);
        return cursor.getString(column_index);
    }

    public int uploadFile(String sourceFileUri, Map<String, String> parmas) {
        String upLoadServerUri = WebServices.LOCAL_UPLOAD_REPORTS;
        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);
        InputStream inputStream = null;
        if (!sourceFile.isFile()) {
            Log.e("uploadFile", "Source File Does not exist");
            return 0;
        }
        try { // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(upLoadServerUri);
            conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
            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("file", fileName);
            dos = new DataOutputStream(conn.getOutputStream());

            String name="_rep"+SafeUtils.getCurrentDateForName(getContext())+SafeUtils.getUserID(getContext());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""+ name+".png" + "\"" + lineEnd);
            dos.writeBytes("Content-Type: " + "images/png" + lineEnd);
            dos.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
            dos.writeBytes(lineEnd);

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

            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);

            // Upload POST Data
            Iterator<String> keys = parmas.keySet().iterator();
            while (keys.hasNext()) {
                String key = keys.next();
                String value = parmas.get(key);

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
                dos.writeBytes("Content-Type: text/plain" + lineEnd);
                dos.writeBytes(lineEnd);
                dos.writeBytes(value);
                dos.writeBytes(lineEnd);
            }


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

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

            Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
            if(serverResponseCode == 200){
                runOnUiThread(new Runnable() {
                    public void run() {
                        //tv.setText("File Upload Completed.");
                        Toast.makeText(getContext(), "File Upload Complete.", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                        finish();
                    }
                });
            }

            inputStream = conn.getInputStream();
            report_id = this.convertStreamToString(inputStream);
            //close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {
            dialog.dismiss();
            ex.printStackTrace();
            Toast.makeText(getContext(), "MalformedURLException", Toast.LENGTH_SHORT).show();
            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {
            dialog.dismiss();
            e.printStackTrace();
            Toast.makeText(getContext(), "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
            Log.e("Upload file", "Exception : " + e.getMessage(), e);
        }
        dialog.dismiss();
        return serverResponseCode;
    }

    private String convertStreamToString(InputStream inputStream) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }