Android在服务器上传图片,图片坏了

时间:2013-11-07 15:02:54

标签: php android image upload

我正在使用方法“uploadAvatar”在我的ubuntu服务器上使用android 4.1和php上传nginx和php-fpm 5.3上的图像。照片被挑选或从相机拍摄,然后被裁剪,保存在文件夹中,然后上传到服务器。

我可以使用图库应用程序在正确的路径中看到手机中的图像。我用图像的绝对路径调用方法然后应用程序开始上传图像,服务器响应200,图像在服务器上但是坏了,我无法用浏览器读取图像。

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

        ProgressDialog_.dismiss();

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

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

        return 0;

    }
    else
    {
        try {

            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(upLoadServerUri);

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

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

                runOnUiThread(new Runnable() {
                    public void run() {

                        /*
                        String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                +" http://www.androidexample.com/media/uploads/"
                                +uploadFileName;

                        //messageText.setText(msg);
                        */

                        Toast.makeText(Register_avatar.this, "File Upload Complete.",
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }

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

        } catch (MalformedURLException ex) {

            ProgressDialog_.dismiss();
            ex.printStackTrace();

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

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

            ProgressDialog_.dismiss();
            e.printStackTrace();

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

    } // End else block
}

这是服务器端PHP脚本:

  

图片已上传但已损坏,在设备上可以正常... 大约2天我正在研究这个问题,有人可以帮助我吗?

您可以在此处看到损坏的图片:http://putp.about42.com/testimage.png

更新:

构建此方法我遵循here的教程:

我在行中发现错误:

dos.writeBytes("Content-Disposition: form-data; name="uploaded_file";filename=""
                                         + fileName + """ + lineEnd);

我改变了这个:

dos.writeBytes("Content-Disposition: form-data; name=uploaded_file;filename=" + fileName + " + lineEnd");

也许破碎的图像依赖于此...我很抱歉,但我不知道这行代码是做什么的......

由于

1 个答案:

答案 0 :(得分:1)

此代码工作正常!

public void uploadAvatar(String sourceFileUri) {

    HttpURLConnection mHttpURLConnection = null;
    DataOutputStream mOutputStream = null;
    String strLineEnd = "\r\n";
    String strTwoHyphens = "--";
    String strUpLoadServerUri = upLoadServerUri;
    String strBoundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);

    if (!sourceFile.isFile()) {

        ProgressDialog_.dismiss();

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

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

    }
    else
    {

        try {

            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(strUpLoadServerUri);

            // Open a HTTP connection to the URL

            mHttpURLConnection = (HttpURLConnection) url
                    .openConnection();
            mHttpURLConnection.setDoInput(true); // Allow Inputs
            mHttpURLConnection.setDoOutput(true); // Allow Outputs
            mHttpURLConnection.setUseCaches(false); // Don't use a Cached Copy

            mHttpURLConnection.setRequestMethod("POST");
            mHttpURLConnection.setRequestProperty("Connection","Keep-Alive");
            mHttpURLConnection.setRequestProperty("ENCTYPE","multipart/form-data");
            mHttpURLConnection.setRequestProperty("Content-Type","multipart/form-data;boundary=" + strBoundary);
            mHttpURLConnection.setRequestProperty("uploaded_file",sourceFileUri);

            mOutputStream = new DataOutputStream(mHttpURLConnection.getOutputStream());

            mOutputStream.writeBytes(strTwoHyphens + strBoundary + strLineEnd);
            mOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename="+ sourceFileUri + strLineEnd);

            mOutputStream.writeBytes(strLineEnd);

            // 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) {

                mOutputStream.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...
            mOutputStream.writeBytes(strLineEnd);
            mOutputStream.writeBytes(strTwoHyphens + strBoundary + strTwoHyphens + strLineEnd);

            // Responses from the server (code and message)
            serverResponseCode = mHttpURLConnection.getResponseCode();

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

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

    if (serverResponseCode == 200) {

        Log.d("File Uploaded For ",sourceFileUri + "   Successful");

        ProgressDialog_.dismiss();

        runOnUiThread(new Runnable() {
            public void run() {

                        /*
                        String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                +" http://www.androidexample.com/media/uploads/"
                                +uploadFileName;

                        //messageText.setText(msg);
                        */

                Toast.makeText(Register_avatar.this, "File Upload Complete.",
                        Toast.LENGTH_SHORT).show();
            }
        });

    }
    else{
        Log.d("File Uploaded For ",sourceFileUri + "   Failed");
        ProgressDialog_.dismiss();

        runOnUiThread(new Runnable() {
            public void run() {

                        /*
                        String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                +" http://www.androidexample.com/media/uploads/"
                                +uploadFileName;

                        //messageText.setText(msg);
                        */

                Toast.makeText(Register_avatar.this, "File Upload Failed.",
                        Toast.LENGTH_SHORT).show();
            }
        });
    }


}

我在代码上做了一些修改,现在它就像一个魅力!

再见