Android文件上传至tomcat,服务端+客户端示例代码

来源:互联网 发布:太阁立志传6比5优化 编辑:程序博客网 时间:2024/05/14 22:37
[java] view plaincopyprint?
  1.   

[plain] view plaincopyprint?
  1. 这个程序在tomcat 5.0服务器环境下成功运行,程序简单,运行效率非常高,非常给力的一个代码,借鉴eoeandroid里大手们的指点,由于本人在J2EE的开发非常不了解,下半年开学~所以jsp什么的显得那么不得心应手,但是一些j2me的知识还是比较熟悉,这个程序非常简单,注释也非常给力~google了半天,感觉肯定会有许多和我一样的菜鸟很需要的。所以贴上来与大家一起分享。  
  2.    
  3.   
  4. 开发这个前一定要手动导入几个必备的jar文件,比如 tomcat下的servlet-api.jar,commons-fileupload-1.2.jar否则无法编译通过,整天开发j2me遇到这些j2ee,真的很不舒服,慢慢习惯就好了~!基本常识吧~  
  5.   
  6. 贴的代码客户端没改,个人习惯把uploadfile()这个方法改成了uploadfile(String url,String filepath)  
  7.   
  8. 从eoe下的原文件  挺好的:http://u.115.com/file/aqzz7pna#  
  9.   
  10. 简单,实用!  
  11.   
  12. 研究了半天webDAV还有那个有名的开源项目slide,无语啊。到最后发现,这个在手机上运行起来效率实在是低下,主要是感觉我们的主要功能不是这个,所以暂时不研究webDAV了~~~不过这个真的是挺经典的一个东西~  
  13.   
  14.    
  15.   
  16. ******************服务器端*************************  








[java] view plaincopyprint?
  1. package net.blogjava.mobile;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.PrintWriter;  
  8. import java.util.List;  
  9.   
  10. import javax.servlet.ServletException;  
  11. import javax.servlet.http.HttpServlet;  
  12. import javax.servlet.http.HttpServletRequest;  
  13. import javax.servlet.http.HttpServletResponse;  
  14.   
  15. import org.apache.commons.fileupload.FileItem;  
  16. import org.apache.commons.fileupload.FileItemFactory;  
  17. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  18. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  19.   
  20. public class UploadServlet extends HttpServlet  
  21. {  
  22. protected void service(HttpServletRequest request,  
  23. HttpServletResponse response) throws ServletException, IOException  
  24. {  
  25. try  
  26. {  
  27. request.setCharacterEncoding("UTF-8"); // 设置处理请求参数的编码格式  
  28. response.setContentType("text/html;charset=UTF-8"); // 设置Content-Type字段值  
  29. PrintWriter out = response.getWriter();  
  30.   
  31. // 下面的代码开始使用Commons-UploadFile组件处理上传的文件数据  
  32. FileItemFactory factory = new DiskFileItemFactory(); // 建立FileItemFactory对象  
  33. ServletFileUpload upload = new ServletFileUpload(factory);  
  34. // 分析请求,并得到上传文件的FileItem对象  
  35. List<FileItem> items = upload.parseRequest(request);  
  36. // 从web.xml文件中的参数中得到上传文件的路径  
  37. String uploadPath = "C:\\tomcat\\webapps\\webdav\\";  
  38. File file = new File(uploadPath);  
  39. if (!file.exists())  
  40. {  
  41. file.mkdir();  
  42. }  
  43. String filename = ""// 上传文件保存到服务器的文件名  
  44. InputStream is = null// 当前上传文件的InputStream对象  
  45. // 循环处理上传文件  
  46. for (FileItem item : items)  
  47. {  
  48. // 处理普通的表单域  
  49. if (item.isFormField())  
  50. {  
  51. if (item.getFieldName().equals("filename"))  
  52. {  
  53. // 如果新文件不为空,将其保存在filename中  
  54. if (!item.getString().equals(""))  
  55. filename = item.getString("UTF-8");  
  56. }  
  57. }  
  58. // 处理上传文件  
  59. else if (item.getName() != null && !item.getName().equals(""))  
  60. {  
  61. // 从客户端发送过来的上传文件路径中截取文件名  
  62. filename = item.getName().substring(  
  63. item.getName().lastIndexOf("\\") + 1);  
  64. is = item.getInputStream(); // 得到上传文件的InputStream对象  
  65. }  
  66. }  
  67. // 将路径和上传文件名组合成完整的服务端路径  
  68. filename = uploadPath + filename;  
  69. // 如果服务器已经存在和上传文件同名的文件,则输出提示信息  
  70. if (new File(filename).exists())  
  71. {  
  72. new File(filename).delete();  
  73. }  
  74. // 开始上传文件  
  75. if (!filename.equals(""))  
  76. {  
  77. // 用FileOutputStream打开服务端的上传文件  
  78. FileOutputStream fos = new FileOutputStream(filename);  
  79. byte[] buffer = new byte[8192]; // 每次读8K字节  
  80. int count = 0;  
  81. // 开始读取上传文件的字节,并将其输出到服务端的上传文件输出流中  
  82. while ((count = is.read(buffer)) > 0)  
  83. {  
  84. fos.write(buffer, 0, count); // 向服务端文件写入字节流  
  85.   
  86. }  
  87. fos.close(); // 关闭FileOutputStream对象  
  88. is.close(); // InputStream对象  
  89. out.println("文件上传成功!");  
  90.   
  91. }  
  92. }  
  93. catch (Exception e)  
  94. {  
  95.   
  96. }  
  97. }}  

********************客户端*****************************

[java] view plaincopyprint?
  1. import java.io.BufferedReader;  
  2. import java.io.DataOutputStream;  
  3. import java.io.FileInputStream;  
  4. import java.io.InputStream;  
  5. import java.io.InputStreamReader;  
  6. import java.net.HttpURLConnection;  
  7. import java.net.URL;  
  8.   
  9. import android.app.Activity;  
  10. import android.app.AlertDialog;  
  11. import android.content.DialogInterface;  
  12. import android.os.Bundle;  
  13. import android.view.View;  
  14. import android.widget.Button;  
  15. import android.widget.TextView;  
  16. import android.widget.Toast;  
  17.   
  18. /* import相关class */  
  19.   
  20. public class EX08_11 extends Activity  
  21. {  
  22. /* 
  23. * 变量声明 filename:上传后在服务器上的文件名称 uploadFile:要上传的文件路径 actionUrl:服务器上对应的程序路径 
  24. */  
  25.   
  26. private String uploadFile = "/sdcard/notepad/txt/213.txt";  
  27. private String srcPath = "/sdcard/notepad/txt/213.txt";  
  28. private String actionUrl = "http://10.0.2.2:8080/upload_file_service/upload.jsp";  
  29. private TextView mText1;  
  30. private TextView mText2;  
  31. private Button mButton;  
  32.   
  33. @Override  
  34. public void onCreate(Bundle savedInstanceState)  
  35. {  
  36. super.onCreate(savedInstanceState);  
  37. setContentView(R.layout.main);  
  38.   
  39. mText1 = (TextView) findViewById(R.id.myText2);  
  40. mText1.setText("文件路径:\n" + uploadFile);  
  41. mText2 = (TextView) findViewById(R.id.myText3);  
  42. mText2.setText("上传网址:\n" + actionUrl);  
  43. /* 设置mButton的onClick事件处理 */  
  44. mButton = (Button) findViewById(R.id.myButton);  
  45. mButton.setOnClickListener(new View.OnClickListener()  
  46. {  
  47. public void onClick(View v)  
  48. {  
  49. uploadFile();  
  50. }  
  51. });  
  52. }  
  53.   
  54. /* 上传文件至Server的方法 */  
  55. private void uploadFile()  
  56. {  
  57.   
  58. String uploadUrl = "http://10.0.2.2:8080/upload_file_service/UploadServlet";  
  59. String end = "\r\n";  
  60. String twoHyphens = "--";  
  61. String boundary = "******";  
  62. try  
  63. {  
  64. URL url = new URL(uploadUrl);  
  65. HttpURLConnection httpURLConnection = (HttpURLConnection) url  
  66. .openConnection();  
  67. httpURLConnection.setDoInput(true);  
  68. httpURLConnection.setDoOutput(true);  
  69. httpURLConnection.setUseCaches(false);  
  70. httpURLConnection.setRequestMethod("POST");  
  71. httpURLConnection.setRequestProperty("Connection""Keep-Alive");  
  72. httpURLConnection.setRequestProperty("Charset""UTF-8");  
  73. httpURLConnection.setRequestProperty("Content-Type",  
  74. "multipart/form-data;boundary=" + boundary);  
  75.   
  76. DataOutputStream dos = new DataOutputStream(httpURLConnection  
  77. .getOutputStream());  
  78. dos.writeBytes(twoHyphens + boundary + end);  
  79. dos  
  80. .writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""  
  81. + srcPath.substring(srcPath.lastIndexOf("/") + 1)  
  82. "\"" + end);  
  83. dos.writeBytes(end);  
  84.   
  85. FileInputStream fis = new FileInputStream(srcPath);  
  86. byte[] buffer = new byte[8192]; // 8k  
  87. int count = 0;  
  88. while ((count = fis.read(buffer)) != -1)  
  89. {  
  90. dos.write(buffer, 0, count);  
  91.   
  92. }  
  93. fis.close();  
  94.   
  95. dos.writeBytes(end);  
  96. dos.writeBytes(twoHyphens + boundary + twoHyphens + end);  
  97. dos.flush();  
  98.   
  99. InputStream is = httpURLConnection.getInputStream();  
  100. InputStreamReader isr = new InputStreamReader(is, "utf-8");  
  101. BufferedReader br = new BufferedReader(isr);  
  102. String result = br.readLine();  
  103.   
  104. Toast.makeText(this, result, Toast.LENGTH_LONG).show();  
  105. dos.close();  
  106. is.close();  
  107.   
  108. catch (Exception e)  
  109. {  
  110. e.printStackTrace();  
  111. setTitle(e.getMessage());  
  112. }  
  113.   
  114. }  
  115.   
  116. }   
原创粉丝点击