java - 上传图片时出现OutOfMemory异常如何解决?

标签 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;
    }
}
}

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

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

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

最佳答案

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 File调整 bitmap 的大小文件以避免此类错误

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

关于java - 上传图片时出现OutOfMemory异常如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27599574/

相关文章:

javax.comm:设备断开连接时出错

java - 如何使用javaGUI(java应用程序)将文件上传到google app引擎

java - 通过独立的java代码访问android的内存

android - 在 Android Studio 中启用 proguard 时构建时出错

JAVA - 尝试使用类外部执行的操作内部的变量

java - 在外部浏览器中从 WebView 打开一些网站页面

android - 如果私钥被盗,我使用 3rd 方 API 的移动应用程序会做什么?

Eclipse tfs : unignore project is disabled

java - 如何升级m2e版本

java - 使用 Java Web App 中的 (Scala) 库,获取 NoClassDefFoundError