发送.txt文件,文档文件,在Android上的服务器 [英] Send .txt file, document file to the server in android

查看:117
本文介绍了发送.txt文件,文档文件,在Android上的服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发中,我以字符串格式将数据发送到服务器上的应用程序。下面是我的code。这是工作的罚款。但现在我的问题是我怎么才可以向整个.txt文件和.doc文件到服务器。在我的GUI我必须提供用户选择的路径。是指用户选择的文件,他/她要传送路径......请帮我解决我的问题......谢谢你......

activity_main.xml文件

 < RelativeLayout的的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    的xmlns:工具=htt​​p://schemas.android.com/tool​​s
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    工具:上下文=MainActivity。>

    <的EditText
        机器人:ID =@ + ID / editText1
        机器人:layout_width =170sp
        机器人:layout_height =40SP
        机器人:layout_alignParentLeft =真
        机器人:layout_alignParentTop =真
        机器人:layout_marginTop =16DP
        机器人:EMS =10
        机器人:提示=@字符串/ IP/>

    <的EditText
        机器人:ID =@ + ID / editText2
        机器人:layout_width =100SP
        机器人:layout_height =40SP
        机器人:layout_alignBaseline =@ + ID / editText1
        机器人:layout_alignBottom =@ + ID / editText1
        机器人:layout_marginLeft =24dp
        机器人:layout_toRightOf =@ + ID / editText1
        机器人:EMS =10
        机器人:提示=@字符串/端口
        机器人:inputType =数字>

        <不是requestFocus />
    < /的EditText>

    <的EditText
        机器人:ID =@ + ID / editText3
        机器人:layout_width =300SP
        机器人:layout_height =200SP
        机器人:layout_below =@ + ID / editText1
        机器人:layout_centerHorizo​​ntal =真
        机器人:layout_marginTop =38dp
        机器人:EMS =10
        机器人:提示=@字符串/味精/>

    <按钮
        机器人:ID =@ + ID /按钮1
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_alignParentBottom =真
        机器人:layout_centerHorizo​​ntal =真
        机器人:layout_marginBottom =64dp
        机器人:文本=@字符串/发送/>

< / RelativeLayout的>
 

.java文件

 进口java.io.IOException异常;
进口的java.io.PrintWriter;
进口的java.net.Socket;
进口的java.net.UnknownHostException;

进口android.os.Bundle;
进口android.app.Activity;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.Button;
进口android.widget.EditText;

公共类MainActivity延伸活动{

    私人客户端的Socket;
    私人PrintWriter的PrintWriter的;
    私人的EditText etMsg,ETIP,etPort;
    私人Button按钮;
    私人字符串消息话题;
    INT端口= 0;

    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);

        ETIP =(EditText上)findViewById(R.id.editText1);
        etPort =(EditText上)findViewById(R.id.editText2);
        etMsg =(EditText上)findViewById(R.id.editText3);
        按钮=(按钮)findViewById(R.id.button1);
        button.setOnClickListener(新OnClickListener(){

            @覆盖
            公共无效的onClick(视图v){
                // TODO自动生成方法存根

                消息话题= etMsg.getText()的toString()。
                etMsg.setText();
                端口=的Integer.parseInt(etPort.getText()的toString());

                新主题(新的Runnable()
                {

                    @覆盖
                    公共无效的run(){
                        // TODO自动生成方法存根
                        尝试
                        {
                            客户端=新的Socket(etIP.getText()的toString(),口);
                            PrintWriter的=的新PrintWriter(client.getOutputStream(),TRUE);
                            printwriter.write(消息话题);
                            printwriter.flush();
                            printwriter.close();
                            client.close();
                        }

                        赶上(UnknownHostException异常E){
                            e.printStackTrace();
                        }赶上(IOException异常E){
                            // TODO自动生成的catch块
                            e.printStackTrace();
                        }
                    }
                })。开始();


            }
        });
    }

}

<使用-权限的Andr​​oid:名称=android.permission.INTERNET对/>
 

解决方案

试试这个code ..这是完全为我工作。

 公共类ServerActivity延伸活动{

    TextView中的MessageText;
    按钮uploadButton;
    INT serverResponse code = 0;
    ProgressDialog对话框= NULL;

    字符串upLoadServerUri = NULL;

    最后弦乐uploadFilePath =mypath中;
     最后弦乐uploadFileName =MYFILE;


    @覆盖
    公共无效的onCreate(包savedInstanceState){

        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_server);

        uploadButton =(按钮)findViewById(R.id.uploadButton);
        =的MessageText(TextView中)findViewById(R.id.messageText);

        messageText.setText(上传文件路径 - 路径+ uploadFileName +');


        upLoadServerUri =SERVERPATH;

        uploadButton.setOnClickListener(新OnClickListener()
        {
            @覆盖
            公共无效的onClick(视图v)
            {

                对话框= ProgressDialog.show(UploadToServer.this,,上传文件...,真正的);

                新主题(新的Runnable()
                {
                        公共无效的run()
                        {
                             runOnUiThread(新的Runnable()
                             {
                                    公共无效的run()
                                    {
                                        messageText.setText(上传开始......);
                                    }
                                });

                             uploadFile(uploadFilePath ++ uploadFileName);

                        }
                      })。开始();
                }
            });
    }

    公众诠释uploadFile(字符串sourceFileUri)
    {


          字符串文件名= sourceFileUri;

          HttpURLConnection的康恩= NULL;
          DataOutputStream类DOS = NULL;
          字符串lineEnd =\ r \ N的;
          串twoHyphens = - ;
          字符串边界=*****;
          INT读取动作,方bytesAvailable,缓冲区大小;
          byte []的缓冲区;
          INT maxBufferSize = 1 * 1024 * 1024;
          文件的SourceFile =新的文件(sourceFileUri);

          如果(!sourceFile.isFile())
          {

               dialog.dismiss();

               Log.e(一个UploadFile,源文件不存在
                                   + uploadFilePath ++ uploadFileName);

               runOnUiThread(新的Runnable()
               {
                   公共无效的run()
                   {
                       messageText.setText(源文件不存在:+ uploadFilePath ++ uploadFileName);
                   }
               });

               返回0;

          }
          其他
          {
               尝试
               {

                     //打开一个URL连接到这个Servlet
                   的FileInputStream的FileInputStream =新的FileInputStream(的资源文件);
                   网址URL =新的URL(upLoadServerUri);

                   //打开一个HTTP连接网址
                   康恩=(HttpURLConnection类)url.openConnection();
                   conn.setDoInput(真正的); //允许输入
                   conn.setDoOutput(真正的); //允许输出
                   conn.setUseCaches(假); //不要使用缓存副本
                   conn.setRequestMethod(POST);
                   conn.setRequestProperty(连接,保持活动);
                   conn.setRequestProperty(ENCTYPE,多部分/表单数据);
                   conn.setRequestProperty(内容类型,多部分/格式数据;边界=+界);
                   conn.setRequestProperty(uploaded_file,文件名);

                   DOS =新DataOutputStream类(conn.getOutputStream());

                   dos.writeBytes(twoHyphens +边界+ lineEnd);
                   dos.writeBytes(内容处置:表格数据;名称= \uploaded_file \;文件名= \
                                             +文件名+\+ lineEnd);

                   dos.writeBytes(lineEnd);

                   //创建最大大小的缓冲区
                   方bytesAvailable = fileInputStream.available();

                   BUFFERSIZE = Math.min(方bytesAvailable,maxBufferSize);
                   缓冲区=新的字节[BUFFERSIZE]

                   //读取文件,并将其写入形式...
                   读取动作= fileInputStream.read(缓冲液,0,BUFFERSIZE);

                   而(读取动作大于0)
                   {

                     dos.write(缓冲液,0,BUFFERSIZE);
                     方bytesAvailable = fileInputStream.available();
                     BUFFERSIZE = Math.min(方bytesAvailable,maxBufferSize);
                     读取动作= fileInputStream.read(缓冲液,0,BUFFERSIZE);

                    }

                   //发送多部分表格数据文件数据后necesssary ...
                   dos.writeBytes(lineEnd);
                   dos.writeBytes(twoHyphens +边界+ twoHyphens + lineEnd);

                   从服务器//回应(code和消息)
                   serverResponse code = conn.getResponse code();
                   串serverResponseMessage = conn.getResponseMessage();

                   Log.i(一个UploadFile,HTTP响应是:
                           + serverResponseMessage +:+ serverResponse code);

                   如果(serverResponse code == 200)
                   {

                       runOnUiThread(新的Runnable()
                       {
                            公共无效的run()
                            {

                                弦乐味精=文件上传已完成\ñ\ñ看到这里上传的文件:\ñ\ N+SERVERPATH
                                              + uploadFileName;

                                messageText.setText(MSG);
                                Toast.makeText(UploadToServer.this,文件上传完成。,
                                             Toast.LENGTH_SHORT).show();
                            }
                        });
                   }

                   //关闭流//
                   fileInputStream.close();
                   dos.flush();
                   dos.close();

              }
               赶上(MalformedURLException的前)
               {

                  dialog.dismiss();
                  ex.printStackTrace();

                  runOnUiThread(新的Runnable()
                  {
                      公共无效的run()
                      {
                          messageText.setText(MalformedURLException的例外情况:检查脚本的网址。);
                          Toast.makeText(UploadToServer.thisMalformedURLException的,Toast.LENGTH_SHORT).show();
                      }
                  });

                  Log.e(上传文件到服务器,错误:+ ex.getMessage(),前);
              }
               赶上(例外五)
               {

                  dialog.dismiss();
                  e.printStackTrace();

                  runOnUiThread(新的Runnable()
                  {
                      公共无效的run()
                      {
                          messageText.setText(GOT例外:看logcat的);
                          Toast.makeText(UploadToServer.this,得到了异常:看logcat的,
                                  Toast.LENGTH_SHORT).show();
                      }
                  });
                  Log.e(上传文件到服务器异常,异常
                                                   + e.getMessage(),E);
              }
              dialog.dismiss();
              返回serverResponse code;

           }
         }
     }
 

希望这将帮助ü: - )

I am developing an application in which I am sending data in string format to the server. Below is my code. It is working fine. But now my question is how can I send whole .txt file and .doc file to the server. In my GUI I have to provide path of user choice. Means user has to choose the path of file that he/she wants to send...Please help me to solve my problem...Thank you...

activity_main.xml file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="170sp"
        android:layout_height="40sp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="@string/ip" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="100sp"
        android:layout_height="40sp"
        android:layout_alignBaseline="@+id/editText1"
        android:layout_alignBottom="@+id/editText1"
        android:layout_marginLeft="24dp"
        android:layout_toRightOf="@+id/editText1"
        android:ems="10"
        android:hint="@string/port"
        android:inputType="number" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText3"
        android:layout_width="300sp"
        android:layout_height="200sp"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="38dp"
        android:ems="10"
        android:hint="@string/msg" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="64dp"
        android:text="@string/send" />

</RelativeLayout>

.java file

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

    private Socket client;
    private PrintWriter printwriter;
    private EditText etMsg, etIP, etPort;
    private Button button;
    private String messsage;
    int port = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etIP = (EditText) findViewById(R.id.editText1);
        etPort = (EditText) findViewById(R.id.editText2);
        etMsg = (EditText) findViewById(R.id.editText3);
        button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                messsage = etMsg.getText().toString();
                etMsg.setText("");
                port = Integer.parseInt(etPort.getText().toString());

                new Thread(new Runnable() 
                {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        try 
                        {
                            client = new Socket(etIP.getText().toString(), port);
                            printwriter = new PrintWriter(client.getOutputStream(),true);
                            printwriter.write(messsage);
                            printwriter.flush();
                            printwriter.close();
                            client.close();
                        }

                        catch (UnknownHostException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }       
                    }
                }).start();


            }
        });
    }

}

<uses-permission android:name="android.permission.INTERNET" />

解决方案

Try this code.. this is perfectly working for me..

public class ServerActivity extends Activity {

    TextView messageText;
    Button uploadButton;
    int serverResponseCode = 0;
    ProgressDialog dialog = null;

    String upLoadServerUri = null;

    final String uploadFilePath = "mypath";
     final String uploadFileName = "myfile";


    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_server);

        uploadButton = (Button)findViewById(R.id.uploadButton);
        messageText  = (TextView)findViewById(R.id.messageText);

        messageText.setText("Uploading file path :- 'path"+uploadFileName+"'");


        upLoadServerUri = "serverpath";

        uploadButton.setOnClickListener(new OnClickListener() 
        {            
            @Override
            public void onClick(View v)
            {

                dialog = ProgressDialog.show(UploadToServer.this, "", "Uploading file...", true);

                new Thread(new Runnable()
                {
                        public void run() 
                        {
                             runOnUiThread(new Runnable() 
                             {
                                    public void run() 
                                    {
                                        messageText.setText("uploading started.....");
                                    }
                                });                      

                             uploadFile(uploadFilePath + "" + uploadFileName);

                        }
                      }).start();        
                }
            });
    }

    public int uploadFile(String sourceFileUri)
    {


          String fileName = sourceFileUri;

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

               dialog.dismiss(); 

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

               runOnUiThread(new Runnable() 
               {
                   public void run() 
                   {
                       messageText.setText("Source File not exist :" +uploadFilePath + "" + uploadFileName);
                   }
               }); 

               return 0;

          }
          else
          {
               try 
               { 

                     // open a URL connection to the Servlet
                   FileInputStream fileInputStream = 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("ENCTYPE", "multipart/form-data");
                   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 = fileInputStream.available(); 

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

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

                   while (bytesRead > 0) 
                   {

                     dos.write(buffer, 0, bufferSize);
                     bytesAvailable = fileInputStream.available();
                     bufferSize = Math.min(bytesAvailable, maxBufferSize);
                     bytesRead = fileInputStream.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)
                   {

                       runOnUiThread(new Runnable() 
                       {
                            public void run()
                            {

                                String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"+" serverpath"
                                              +uploadFileName;

                                messageText.setText(msg);
                                Toast.makeText(UploadToServer.this, "File Upload Complete.", 
                                             Toast.LENGTH_SHORT).show();
                            }
                        });                
                   }    

                   //close the streams //
                   fileInputStream.close();
                   dos.flush();
                   dos.close();

              } 
               catch (MalformedURLException ex) 
               {

                  dialog.dismiss();  
                  ex.printStackTrace();

                  runOnUiThread(new Runnable() 
                  {
                      public void run() 
                      {
                          messageText.setText("MalformedURLException Exception : check script url.");
                          Toast.makeText(UploadToServer.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                      }
                  });

                  Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
              } 
               catch (Exception e) 
               {

                  dialog.dismiss();  
                  e.printStackTrace();

                  runOnUiThread(new Runnable() 
                  {
                      public void run()
                      {
                          messageText.setText("Got Exception : see logcat ");
                          Toast.makeText(UploadToServer.this, "Got Exception : see logcat ", 
                                  Toast.LENGTH_SHORT).show();
                      }
                  });
                  Log.e("Upload file to server Exception", "Exception : " 
                                                   + e.getMessage(), e);  
              }
              dialog.dismiss();       
              return serverResponseCode; 

           } 
         }
     }

Hope this will help u :-)

这篇关于发送.txt文件,文档文件,在Android上的服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆