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

Php 在Android中将图像从文件夹上载到服务器,php,android,httpurlconnection,multipartform-data,Php,Android,Httpurlconnection,Multipartform Data,我曾尝试将自定义文件夹中的图像上载到服务器,但按下上载按钮时应用程序崩溃。 我在谷歌上搜索过,但找不到关于相同需求的适当资源/指针。 使用“多部分”同时发送多个图像。 代码如下: public class MainActivity extends AppCompatActivity { private static final String IMAGE_DIRECTORY = "SyncCam"; private Button btn;

我曾尝试将自定义文件夹中的图像上载到服务器,但按下上载按钮时应用程序崩溃。 我在谷歌上搜索过,但找不到关于相同需求的适当资源/指针。 使用“多部分”同时发送多个图像。 代码如下:

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

            }
        }
上面的代码正确吗?
是否需要进行任何更改?

它正在崩溃,因为您正在绑定在主线程上进行网络调用。尝试使用AsyncTask进行上载。

它正在崩溃,因为您正在绑定在主线程上进行网络调用。尝试使用异步任务进行上传。

应用程序仍然会使用异步任务崩溃。通过使用“doInBackground”函数调用。您可以提供崩溃日志吗?应用程序仍然使用异步任务崩溃。通过使用“doInBackground”函数调用。您可以提供崩溃日志吗?
    $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";
    }
 ?>