将图像上传到服务器时出现android java.io.eof错误

时间:2014-04-04 11:53:47

标签: java android eof

我一直在玩这段代码已经有好几个小时了,我似乎无法解决文件错误的结束。

要点是,您可以从图库中选择一个文件,或者使用相机拍摄一个文件,然后将其上传到服务器。

在检查http响应代码后,我一直在点击异常。

任何人都可以了解最新情况吗?我一直希望能看到明显的想法!

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.zelphe.zelpheapp.library.OtherFunctions;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HomeFragment extends Fragment
{



    public HomeFragment(){}

    TextView userCompleteName;
    ImageView userImage;

    int serverResponseCode = 0;
    ProgressDialog dialog = null;

    String uFP, uFN, userID, userFirstName, userLastName;
    String upLoadServerUri = "http://zelphe.com/app/profilepicupload.php";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_home, container, false);
        userID = this.getArguments().getString("USER_ID");
        userFirstName = this.getArguments().getString("USER_FN");
        userLastName = this.getArguments().getString("USER_LN");

        userImage = (ImageView) rootView.findViewById(R.id.userImage);



        userImage.setOnClickListener(new View.OnClickListener()
        {

            @Override

            public void onClick(View v)
            {

                selectImage();

            }

        });
        return rootView;
    }


        private void selectImage()
        {
            final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
            AlertDialog.Builder builder;
            builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("Add Photo!");
            builder.setItems(options, new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int item)
                {
                    if (options[item].equals("Take Photo"))
                    {
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                        //pic = f;
                        startActivityForResult(intent, 1);
                     }

                    else if (options[item].equals("Choose from Gallery"))
                    {
                        Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent, 2);
                    }

                    else if (options[item].equals("Cancel"))
                    {

                        dialog.dismiss();

                    }

                }

            });

            builder.show();

        }

    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == 1)
            {
                if (resultCode == Activity.RESULT_OK)
                {
                    File f = new File(Environment.getExternalStorageDirectory().toString());
                    for (File temp : f.listFiles())
                    {
                        if (temp.getName().equals("temp.jpg"))
                            {
                                f = temp;
                                File photo = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
                                //pic = photo;
                                break;
                            }
                    }

                    try
                    {
                        Bitmap bitmap;
                        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
                        bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions);
                        userImage.setImageBitmap(bitmap);
                        OtherFunctions otF = new OtherFunctions();
                        String path = null;
                        if (otF.isExternalAvail() == true)
                            {
                                path = android.os.Environment.getExternalStorageDirectory() + File.separator + "Zelphe" + File.separator + "default";
                            }
                        else
                            {
                             //todo later
                            }

                            File p = new File(path);
                        if (!p.exists())
                        {
                            p.mkdirs();

                        }
                            f.delete();

                        if (p.isDirectory()) {
                            String[] children = p.list();
                            for (int i = 0; i < children.length; i++) {
                                new File(p, children[i]).delete();
                            }
                        }
                            OutputStream outFile = null;
                            File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                            uploadprofileimage(file);
                                try
                                    {
                                        outFile = new FileOutputStream(file);
                                        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                                        //pic=file;
                                        outFile.flush();
                                        outFile.close();
                                    }
                                catch (FileNotFoundException e)
                                    {
                                        e.printStackTrace();
                                    }
                                catch (IOException e)
                                    {
                                        e.printStackTrace();
                                    }
                                catch (Exception e)
                                    {
                                        e.printStackTrace();
                                    }
                    }
                        catch (Exception e)
                            {
                                e.printStackTrace();
                            }
            }
        }

    else if (requestCode == 2){
            if (resultCode == Activity.RESULT_OK) {
                Uri selectedImage = data.getData();
                // h=1;
                //imgui = selectedImage;
                String[] filePath = { MediaStore.Images.Media.DATA };

                Cursor c = getActivity().getContentResolver().query(selectedImage,filePath, null, null, null);

                c.moveToFirst();

                int columnIndex = c.getColumnIndex(filePath[0]);

                String picturePath = c.getString(columnIndex);

                c.close();

                Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));


                Log.w("path of image from gallery......******************.........", picturePath + "");


                userImage.setImageBitmap(thumbnail);
                File file = new File(picturePath);
                uploadprofileimage(file);
            }
        }

        else if (requestCode == 3)
        {
            if (resultCode == Activity.RESULT_OK) {
                String result = data.getStringExtra("result");
            }

            if (resultCode == Activity.RESULT_CANCELED) {
                //Write your code if there's no result
            }
        }
    }

    private void uploadprofileimage(final File profileimage) {

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

                 uFP = profileimage.getPath();
                 uFN = profileimage.getName();
                uploadFile(uFP);

            }
        }).start();
    }


    public int uploadFile(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 :"
                    +uFP + "" + uFN);



            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);
                conn.setRequestProperty("userid", userID);

                dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=" + fileName + ";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){

                //done!
                }

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

            } catch (MalformedURLException ex) {

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



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

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


                Log.e("Upload file to server Exception", "Exception : "
                        + e.getMessage(), e);
            }
            dialog.dismiss();
            return serverResponseCode;

        } // End else block
    }
}

1 个答案:

答案 0 :(得分:1)

在http连接中添加以下行

   conn.setRequestProperty("Connection", "close");