0
  1. 打开图库应用

                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                dialog1.dismiss();
                startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
    
  2. 选择 Goes to OnActivityResult 后

            selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
    
            if(selectedImagePath==null)
            {
                Toast.makeText(MyProfileNewActivity.this, "Wrong File Please Select From Gallery", Toast.LENGTH_SHORT).show();
            }
            else
            {
    
                UploadProfilePicGallery uppg=new UploadProfilePicGallery();
                uppg.execute();
            }**
    
  3. 使用 AndroidMultiPartEntity 启动 Asynctask 以将图像上传到服务器

      public class UploadProfilePicGallery extends AsyncTask<Void,String,String>
        {
    
    @Override
    protected String doInBackground(Void... voids) {
    
        //sourceFileUri.replace(sourceFileUri, "jagan");
        //
    
        int day, month, year;
        int second, minute, hour;
        GregorianCalendar date = new GregorianCalendar();
    
        day = date.get(Calendar.DAY_OF_MONTH);
        month = date.get(Calendar.MONTH);
        year = date.get(Calendar.YEAR);
    
        second = date.get(Calendar.SECOND);
        minute = date.get(Calendar.MINUTE);
        hour = date.get(Calendar.HOUR);
    
        String name = (hour + "" + minute + "" + second + "" + day + "" + (month + 1) + "" + year);
        String tag = name + ".jpg";
        String fileName = selectedImagePath.replace(selectedImagePath, tag);
    
        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(selectedImagePath);
        try {
            Bitmap bmp = BitmapFactory.decodeFile(sourceFile.getAbsolutePath());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] bitmapdata = bos.toByteArray();
            bmp.compress(Bitmap.CompressFormat.JPEG, 10, bos);
            bmp.compress(Bitmap.CompressFormat.JPEG, 10, bos);
            bmp = getResizedBitmap(bmp, 100);
            bitmapdata=bos.toByteArray();
            bProfileBitmap=bmp;
            FileOutputStream fos= null;
            try {
                fos = new FileOutputStream(sourceFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
    
            try {
                fos.write(bitmapdata);
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        catch(OutOfMemoryError o)
        {
            return "Out Of Memory Error";
        }
    
    
    
        if (!sourceFile.isFile()) {
    
            // dialog.dismiss();
    
            Log.e("uploadFile", "Source File not exist :" + "");
            result="file missing";
            return result;
    
        } else {
            try {
    
                // open a URL connection to the Servlet
                File sourceFile1 = new File(selectedImagePath);
                FileInputStream fileInputStream = new FileInputStream(sourceFile1);
                URL url = new URL(URLPath+"FileUploadGallery.php");
    
                // 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); //===============
                session.setPicName(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();
                String serverResponseMessage = conn.getResponseMessage();
    
                Log.i("uploadFile", "HTTP Response is : "
                        + serverResponseMessage + ": " + serverResponseCode);
    
                if (serverResponseCode == 200) {
                    result= "File Upload Completed";
                }
    
                //close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();
    
            } catch (MalformedURLException ex) {
                ex.printStackTrace();
                result ="MalformedURLException";
                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
            } catch (Exception e) {
                e.printStackTrace();
                result = "Exception";
                Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
            }
            return result;
        }
    }
    
  4. 注意只有当用户选择相机拍摄的图像时才会出现错误......除此之外,下载的图像可以从图库中上传。(有时崩溃有时OutOfMemoryErrorOccurs)

请给我一个解决方案,我在这个问题上工作了 3 天以上,但我无法找出问题所在........如果您有任何其他代码真的很好,请与我分享....

4

2 回答 2

1

使用Multipart上传图像。单击此处查看完整示例。

于 2016-04-05T05:33:10.593 回答
0

只需通过更改您的 Intent 来尝试此操作。可能会有所帮助

 Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
 startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
于 2016-04-05T05:11:36.063 回答