在Android中将图像从文件夹上载到服务器

时间:2016-02-26 00:24:53

标签: php android httpurlconnection multipartform-data

我尝试将图片从自定义文件夹上传到服务器,但按下上传按钮时应用程序崩溃了。 我用谷歌搜索,但无法找到有关相同要求的适当资源/指针。 使用“multipart”同时发送多个图像。 这是代码:

public class MainActivity extends AppCompatActivity
    {

        private static final String IMAGE_DIRECTORY = "SyncCam";
        private Button btn;

        String upLoadServerUri = "http://x.x.x.x/Sync/Sync.php";

        /**********  File Path *************/

        final String uploadFilePath = "/storage/sdcard0/SyncCam/";
        final String uploadFileName = "";
        int serverResponseCode = 0;

        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            btn = (Button) findViewById(R.id.cam_btn);

            btn.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    uploadFile("");
                }
            });

            String path = Environment.getExternalStorageDirectory().toString() + IMAGE_DIRECTORY;
            File f = new File(path);
            File imgPaths[] = f.listFiles();
            //Log.d("");
            for (int i = 0; i < imgPaths.length; i++)
            {
                Log.d("Files", "FileName:" + imgPaths[i].getName());
                uploadFile(uploadFilePath + "" + imgPaths[i].getName());
            }
        }



            public void uploadFile(String sourceFileUri)
            {

                String fileName = sourceFileUri;
                HttpURLConnection conn;
                DataOutputStream dos;
                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())
                {

                    Log.e("uploadFile", "Source File not exist :" + uploadFilePath + "" + uploadFileName);
                    //return 0;

                }
                else
                {
                    try
                    {
                        // open a URL connection to the Servlet
                        FileInputStream fis = 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("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 = fis.available();

                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        buffer = new byte[bufferSize];

                        // read file and write it into form...
                        bytesRead = fis.read(buffer, 0, bufferSize);

                        while (bytesRead > 0)
                        {

                            dos.write(buffer, 0, bufferSize);
                            bytesAvailable = fis.available();
                            bufferSize = Math.min(bytesAvailable, maxBufferSize);
                            bytesRead = fis.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)
                        {
                            Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                        }
                        //close the streams //
                        fis.close();
                        dos.flush();
                        dos.close();
                    }
                    catch (MalformedURLException ex)
                    {
                        ex.printStackTrace();
                        Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                        Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                        Toast.makeText(MainActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
                        Log.e(e.getMessage(), "");
                    }

                    //return serverResponseCode;

                } // End else block

            }
        }

以下是相应的PHP代码:     

    $file_path = "Sync/";
    $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) 
    {
        echo "success";
    } 
    else
    {
        echo "fail";
    }
 ?>

以上代码是否正确? 是否需要进行任何更改?

1 个答案:

答案 0 :(得分:0)

它正在崩溃,因为你想要在主线程上进行网络调用。尝试使用AsyncTask进行上传。