【问题标题】:How to solve OutOfMemory Exception when uploading image?上传图片时如何解决OutOfMemory Exception?
【发布时间】:2014-12-22 09:08:39
【问题描述】:

我能够将文件大小可能小于 1Mb 的图像上传到服务器,如果我上传超过 1Mb,则会出现 OutOfMemory 错误。我已经使用 BitmapFactory 对文件进行解码,但仍然无法上传大图像文件。

12-15 22:33:51.465: E/AndroidRuntime(11968): java.lang.OutOfMemoryError
12-15 22:33:51.465: E/AndroidRuntime(11968):    at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
12-15 22:33:51.465: E/AndroidRuntime(11968):    at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:652)
12-15 22:33:51.465: E/AndroidRuntime(11968):    at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:391)
12-15 22:33:51.465: E/AndroidRuntime(11968):    at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:451)
12-15 22:33:51.465: E/AndroidRuntime(11968):    at sp.com.NewProductActivity.onActivityResult(NewProductActivity.java:137)
12-15 22:33:51.465: E/AndroidRuntime(11968):    at android.app.Activity.dispatchActivityResult(Activity.java:5390)
12-15 22:33:51.465: E/AndroidRuntime(11968):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3201)
12-15 22:33:51.465: E/AndroidRuntime(11968):    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3248)
12-15 22:33:51.465: E/AndroidRuntime(11968):    at android.app.ActivityThread.access$1200(ActivityThread.java:140)
12-15 22:33:51.465: E/AndroidRuntime(11968):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1285)
12-15 22:33:51.465: E/AndroidRuntime(11968):    at android.os.Handler.dispatchMessage(Handler.java:99)
12-15 22:33:51.465: E/AndroidRuntime(11968):    at android.os.Looper.loop(Looper.java:137)
12-15 22:33:51.465: E/AndroidRuntime(11968):    at android.app.ActivityThread.main(ActivityThread.java:4921)
12-15 22:33:51.465: E/AndroidRuntime(11968):    at java.lang.reflect.Method.invokeNative(Native Method)
12-15 22:33:51.465: E/AndroidRuntime(11968):    at java.lang.reflect.Method.invoke(Method.java:511)
12-15 22:33:51.465: E/AndroidRuntime(11968):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
12-15 22:33:51.465: E/AndroidRuntime(11968):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
12-15 22:33:51.465: E/AndroidRuntime(11968):    at dalvik.system.NativeStart.main(Native Method)

NewProductActivity.java

public int uploadFile(final 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()) {

        dialog.dismiss();

        Log.e("uploadFile", "Source File not exist :" + imagepath);

        runOnUiThread(new Runnable() {
            public void run() {
                messageText.setText("Source File not exist :" + imagepath);
            }
        });

        return 0;

    } else {
        try {

            // Edit Text
            inputName = (EditText) findViewById(R.id.inputName);
            inputLocation = (EditText) findViewById(R.id.inputLocation);
            inputDesc = (EditText) findViewById(R.id.inputDesc);

            //Radio Button
            reportTypeGroup = (RadioGroup) findViewById(R.id.typeOfReport);
            reportType = "";

            switch (reportTypeGroup.getCheckedRadioButtonId()) {

            case R.id.hazard:
                reportType = "Hazard";
                break;

            case R.id.incident:
                reportType = "Incident";
                break;

            default:
                reportType = "Unknown";
                break;
            }

            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(upLoadServerUri);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
           // conn.setChunkedStreamingMode(1024);
            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);

//Adding Parameters

            dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"name\""
                    + lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(inputName.getText().toString());
            dos.writeBytes(lineEnd);

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=location"
                    + lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(inputLocation.getText().toString());
            dos.writeBytes(lineEnd);

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=description"
                    + lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(inputDesc.getText().toString());
            dos.writeBytes(lineEnd);

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=type"
                    + lineEnd);
            dos.writeBytes(lineEnd);
            dos.writeBytes(reportType.toString());
            dos.writeBytes(lineEnd);

//Adding Parameter media file(audio,video and image)

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


            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

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

            if (serverResponseCode == 200) {

                runOnUiThread(new Runnable() {
                    public void run() {
                        String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                + "c:/wamp/www/echo/uploads";
                        messageText.setText(msg);
                        Toast.makeText(NewProductActivity.this,
                                "File Upload Complete.", Toast.LENGTH_SHORT)
                                .show();
                    }
                });
            }

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

        } catch (MalformedURLException ex) {

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

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText
                            .setText("MalformedURLException Exception : check script url.");
                    Toast.makeText(NewProductActivity.this,
                            "MalformedURLException", Toast.LENGTH_SHORT)
                            .show();
                }
            });

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

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

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

--------编辑-------- 添加以下代码后,我不再收到 OutOfMemory 异常,并显示“上传成功”,但没有上传任何内容。

 final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;

Bitmap bm = BitmapFactory.decodeFile(strPath,options);
imageView.setImageBitmap(bm);

【问题讨论】:

    标签: java android eclipse upload


    【解决方案1】:

    1. 对于内存不足错误,请将以下行添加到 Manifest 文件中的 <application> 标记中-

    `<application
          ...
          android:largeHeap="true"
     </application>`
    

    2.你的编程方式对于布局初始化是完全错误的

     inputName = (EditText) findViewById(R.id.inputName);
     inputLocation = (EditText) findViewById(R.id.inputLocation);
     inputDesc = (EditText) findViewById(R.id.inputDesc);
    

    这应该在onCreate(Bundle arg0) 中以获得最佳实践 还有一个像上传图片的过程,你必须使用 AsyncTask 前:How can I use an Async Task to upload FileResize 你的 bitmap 文件以避免此类错误

    3.对于大图像问题,您必须更改 php 服务器的设置。 默认情况下,http 请求允许在 php 服务器上上传高达 2 mb 的数据。如果您想增加上传限制,请转到您的 php 配置文件并将上传限制设置为您想要的。

    【讨论】:

      【解决方案2】:

      使用 AsyncTask 上传图片。因为你不能在 UI 线程上做上传和下载任务。

      【讨论】:

      • 这个答案部分正确:可以在 ui 线程上执行长时间运行的操作,尽管这是一种非常糟糕的做法,甚至更新版本的 lint 也会抱怨它。
      • 我会进行图像处理(调整大小、压缩),并按照您的建议通过AsyncTask 上传。对不起,如果我让你感到困惑,你的答案是正确的,只是有点误导。
      • @rekaszeru .. 哦,没关系...但是有一种方法可以通过universal-image-loader之类的库上传或下载图像...
      • 做同样的事情。
      【解决方案3】:

      您需要调整位图的大小来解决这个问题,但在此之前只需尝试一件事,在 Android 清单的应用程序标记中添加 largeHeap = true 标记。

      【讨论】:

        猜你喜欢
        • 2019-06-19
        • 2019-04-02
        • 1970-01-01
        • 1970-01-01
        • 2021-04-19
        • 2021-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多