简体   繁体   English

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

[英]Uploading Images from a Folder to Server in Android

I have tried to upload the Images from Custom Folder to Server but the app crashes when pressing on Upload Button. 我试图将图像从“自定义文件夹”上传到服务器,但是按“上传”按钮时,应用程序崩溃。 I have googled but couldn't find proper resource / pointers regarding the same requirement. 我已经用谷歌搜索,但是找不到关于相同要求的正确资源/指针。 Using "multipart" to send multiple images at the same time. 使用“多部分”同时发送多个图像。 Here is the Code : 这是代码:

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

            }
        }

Here is the corresponidng PHP Code : 这是对应的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";
    }
 ?>

Is the above code correct? 以上代码是否正确? Are there any changes need to be made? 是否需要进行任何更改?

It is crashing because you are tying to do a network call on the main thread. 它崩溃是因为您想在主线程上进行网络调用。 Try using an AsyncTask for the upload. 尝试使用AsyncTask进行上传。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM