浏览文件并通过套接字将其上传到服务器

时间:2015-04-21 19:38:48

标签: android sockets file-upload file-browser

我正在开发一个应用程序,它允许用户浏览存储中的文件(内部/外部)并将其上传到java Serversocket。

谢谢。

这是我的文件选择器代码

public String fileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("file/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    startActivityForResult(Intent.createChooser(intent, "Choose Your File"), 1);


}

应用程序不断崩溃.....我做错了什么? 好吧我发现应用程序崩溃是因为我试图在方法本身中返回URI。然后我对其进行了修改,以便在用户从选择器中选择文件时获取它。

但是现在我正在托管一个Socket服务器,它将接收文件(任何文件文本/多媒体)并将其存储到特定目录中。

我的接收者如下:

public void step1()
{
   File theDir = new File("C://ServerFiles");
     if (!theDir.exists()) {
    try{
        theDir.mkdir();

     } catch(SecurityException se){
        areaStatus.append("error creating file \n");
     }        
  }

      try {
                    InetAddress IP=InetAddress.getLocalHost();
                    lblIp.setText("IP:"+IP.toString());
                } catch (UnknownHostException ex) {
                    Logger.getLogger(ServerConfig.class.getName()).log(Level.SEVERE, null, ex);
                }
        try {
            areaStatus.append("ServerRunning.... \n");
            String SPort;
            SPort = txtport.getText();
            Serverport  =Integer.parseInt(SPort);
            serverSocket = new ServerSocket(Serverport);

             ClientSocket=serverSocket.accept();
            areaStatus.append("Connected With"+ClientSocket.getInetAddress().toString()+"\n");

             input = ClientSocket.getInputStream();
            BufferedReader inReader = new BufferedReader(new InputStreamReader(ClientSocket.getInputStream()));
            BufferedWriter outReader = new BufferedWriter(new OutputStreamWriter(ClientSocket.getOutputStream()));

            filename = inReader.readLine();

            if ( !filename.equals("") ){



                outReader.write("READY\n");
                outReader.flush();
            }
        } catch (IOException ex) {
            Logger.getLogger(ServerConfig.class.getName()).log(Level.SEVERE, null, ex);
        }

areaStatus.append("Client connected \n");   


}

public void step2()
{
     byte[] buffer;
     buffer= null;
    FileOutputStream wr = null;

        try {
            wr = new FileOutputStream(new File("C://ServerFiles/" + filename));
        try {
            buffer = new byte[ClientSocket.getReceiveBufferSize()];
        } catch (SocketException ex) {
            Logger.getLogger(ServerConfig.class.getName()).log(Level.SEVERE, null, ex);
        }
            int bytesReceived = 0;
        try {
            while((bytesReceived = input.read(buffer))>0)
            {
                /* Write to the file */
                wr.write(buffer,0,bytesReceived);
            }
        } catch (IOException ex) {
            Logger.getLogger(ServerConfig.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            wr.close();
        } catch (IOException ex) {
            Logger.getLogger(ServerConfig.class.getName()).log(Level.SEVERE, null, ex);
        }
        areaStatus.append("Transfer completed \n");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ServerConfig.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                wr.close();
            } catch (IOException ex) {
           Logger.getLogger(ServerConfig.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

}
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        step1();           

    }                              


        }
    }

我正在处理文件发件人,我会在完成后立即发帖。

这是我的文件发件人,但它显示的是找不到文件错误:

 private class Fileuploader extends AsyncTask<Void, Void, Integer> {

        protected void onPreExecute() {
        }

        protected Integer doInBackground(Void... params) {

            Socket sk;

            try {
                sk = new Socket("192.168.0.108", 1131);

                File myFile = new File(filepathString);
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = new FileInputStream(myFile);
                BufferedInputStream bis = new BufferedInputStream(fis);
                bis.read(mybytearray, 0, mybytearray.length);

                OutputStream os = sk.getOutputStream();

                os.write(mybytearray, 0, mybytearray.length);

                os.flush();

                sk.close();




            } catch (IOException e) {
                e.printStackTrace();
            }




            return 1;
        }

        protected void onPostExecute(Integer result) {

        }
    }

我的ADB日志:

04-22 13:23:14.269    8355-8385/envoyone.ak.ace.fileud I/OpenGLRenderer﹕ Initialized EGL, version 1.4
04-22 13:23:14.299    8355-8385/envoyone.ak.ace.fileud D/OpenGLRenderer﹕ Enabling debug mode 0
04-22 13:23:16.860    8355-8355/envoyone.ak.ace.fileud W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
04-22 13:23:24.745    8355-8387/envoyone.ak.ace.fileud W/System.err﹕ java.io.FileNotFoundException: content:/com.android.externalstorage.documents/document/primary%3Atext%2Fmessenger_dndictionary.xml: open failed: ENOENT (No such file or directory)
04-22 13:23:24.757    8355-8387/envoyone.ak.ace.fileud W/System.err﹕ at libcore.io.IoBridge.open(IoBridge.java:456)
04-22 13:23:24.757    8355-8387/envoyone.ak.ace.fileud W/System.err﹕ at java.io.FileInputStream.<init>(FileInputStream.java:76)
04-22 13:23:24.757    8355-8387/envoyone.ak.ace.fileud W/System.err﹕ at envoyone.ak.ace.fileud.FileUpload$Fileuploader.doInBackground(FileUpload.java:98)
04-22 13:23:24.757    8355-8387/envoyone.ak.ace.fileud W/System.err﹕ at envoyone.ak.ace.fileud.FileUpload$Fileuploader.doInBackground(FileUpload.java:78)
04-22 13:23:24.757    8355-8387/envoyone.ak.ace.fileud W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:288)
04-22 13:23:24.757    8355-8387/envoyone.ak.ace.fileud W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
04-22 13:23:24.757    8355-8387/envoyone.ak.ace.fileud W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
04-22 13:23:24.759    8355-8387/envoyone.ak.ace.fileud W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
04-22 13:23:24.759    8355-8387/envoyone.ak.ace.fileud W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
04-22 13:23:24.759    8355-8387/envoyone.ak.ace.fileud W/System.err﹕ at java.lang.Thread.run(Thread.java:818)
04-22 13:23:24.759    8355-8387/envoyone.ak.ace.fileud W/System.err﹕ Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
04-22 13:23:24.760    8355-8387/envoyone.ak.ace.fileud W/System.err﹕ at libcore.io.Posix.open(Native Method)
04-22 13:23:24.760    8355-8387/envoyone.ak.ace.fileud W/System.err﹕ at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
04-22 13:23:24.760    8355-8387/envoyone.ak.ace.fileud W/System.err﹕ at libcore.io.IoBridge.open(IoBridge.java:442)
04-22 13:23:24.760    8355-8387/envoyone.ak.ace.fileud W/System.err﹕ ... 9 more
04-22 13:23:54.924    8355-8355/envoyone.ak.ace.fileud W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection

1 个答案:

答案 0 :(得分:1)

图库项目只是图片和视频。 你有几个选择。

1)使用其他应用程序选择文件

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, PICKFILE_RESULT_CODE);

这将打开可以浏览文件的应用列表。可以从该界面中选择一个文件

2)使用存储访问框架。它类似于第1点。但界面由android本身提供。 Read more

3)使用File对象访问外部存储目录。必须在清单

中添加以下权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

然后,下面将给出一个指向主外部存储目录的文件对象,从该目录可以访问整个文件系统。

File file = new File(Environment. getExternalStorageDirectory ());
  

注意:不要被&#34;外部&#34;这个词弄糊涂。这里。此目录最好被视为媒体/共享存储。它是一个文件系统,可以容纳相对大量的数据,并在所有应用程序之间共享(不强制执行权限)。传统上这是一张SD卡,但它也可以作为内置存储器实现,该设备不同于受保护的内部存储器,可以作为文件系统安装在计算机上。

要从可移动microSD卡访问文件,请按this answer