上传图片时如何解决OutOfMemory异常?

时间:2014-12-22 09:08:39

标签: java android eclipse upload

我能够将文件大小小于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;
    }
}
}

------- -------- EDIT 添加以下代码后,我不再获得OutOfMemory异常并且说“上传成功”,但没有上传任何内容。

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

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

3 个答案:

答案 0 :(得分:8)

内存不足的

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 ex How can I use an Async Task to upload File调整大小你的bitmap文件以避免此类错误

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

答案 1 :(得分:1)

使用AsyncTask上传图片..因为您无法在UI线程上执行上传和下载任务。

答案 2 :(得分:0)

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