发送.txt文件,将文件文件发送到android中的服务器

发送.txt文件,将文件文件发送到android中的服务器,第1张

概述我正在开发一个应用程序,我在其中以字符串格式向服务器发送数据.以下是我的代码.它工作正常.但现在我的问题是如何将整个.txt文件和.doc文件发送到服务器.在我的GUI中,我必须提供用户选择的路径.意味着用户必须选择他/她想要发送的文件的路径…请帮我解决我的问题…谢谢……activi

我正在开发一个应用程序,我在其中以字符串格式向服务器发送数据.以下是我的代码.它工作正常.但现在我的问题是如何将整个.txt文件和.doc文件发送到服务器.在我的GUI中,我必须提供用户选择的路径.意味着用户必须选择他/她想要发送的文件的路径…请帮我解决我的问题…谢谢……

activity_main.xml文件

<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文件

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" />

解决方法:

试试这个代码..这对我来说非常合适..

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;            }          }     }

希望这会对你有所帮助:-)

总结

以上是内存溢出为你收集整理的发送.txt文件,将文件文件发送到android中的服务器全部内容,希望文章能够帮你解决发送.txt文件,将文件文件发送到android中的服务器所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1116022.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存