dongwuchu0314 2016-02-26 00:24
浏览 72

在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 = "
";
                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 :

    $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?

  • 写回答

1条回答 默认 最新

  • doufen3134 2016-02-26 01:03
    关注

    It is crashing because you are tying to do a network call on the main thread. Try using an AsyncTask for the upload.

    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行