- 这个程序在tomcat 5.0服务器环境下成功运行,程序简单,运行效率非常高,非常给力的一个代码,借鉴eoeandroid里大手们的指点,由于本人在J2EE的开发非常不了解,下半年开学~所以jsp什么的显得那么不得心应手,但是一些j2me的知识还是比较熟悉,这个程序非常简单,注释也非常给力~google了半天,感觉肯定会有许多和我一样的菜鸟很需要的。所以贴上来与大家一起分享。
- 开发这个前一定要手动导入几个必备的jar文件,比如 tomcat下的servlet-api.jar,commons-fileupload-1.2.jar否则无法编译通过,整天开发j2me遇到这些j2ee,真的很不舒服,慢慢习惯就好了~!基本常识吧~
- 贴的代码客户端没改,个人习惯把uploadfile()这个方法改成了uploadfile(String url,String filepath)
- 从eoe下的原文件 挺好的:http://u.115.com/file/aqzz7pna#
- 简单,实用!
- 研究了半天webDAV还有那个有名的开源项目slide,无语啊。到最后发现,这个在手机上运行起来效率实在是低下,主要是感觉我们的主要功能不是这个,所以暂时不研究webDAV了~~~不过这个真的是挺经典的一个东西~
- ******************服务器端*************************
- package net.blogjava.mobile;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.PrintWriter;
- import java.util.List;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.commons.fileupload.FileItem;
- import org.apache.commons.fileupload.FileItemFactory;
- import org.apache.commons.fileupload.disk.DiskFileItemFactory;
- import org.apache.commons.fileupload.servlet.ServletFileUpload;
- public class UploadServlet extends HttpServlet
- {
- protected void service(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException
- {
- try
- {
- request.setCharacterEncoding("UTF-8"); // 设置处理请求参数的编码格式
- response.setContentType("text/html;charset=UTF-8"); // 设置Content-Type字段值
- PrintWriter out = response.getWriter();
- // 下面的代码开始使用Commons-UploadFile组件处理上传的文件数据
- FileItemFactory factory = new DiskFileItemFactory(); // 建立FileItemFactory对象
- ServletFileUpload upload = new ServletFileUpload(factory);
- // 分析请求,并得到上传文件的FileItem对象
- List<FileItem> items = upload.parseRequest(request);
- // 从web.xml文件中的参数中得到上传文件的路径
- String uploadPath = "C:\\tomcat\\webapps\\webdav\\";
- File file = new File(uploadPath);
- if (!file.exists())
- {
- file.mkdir();
- }
- String filename = ""; // 上传文件保存到服务器的文件名
- InputStream is = null; // 当前上传文件的InputStream对象
- // 循环处理上传文件
- for (FileItem item : items)
- {
- // 处理普通的表单域
- if (item.isFormField())
- {
- if (item.getFieldName().equals("filename"))
- {
- // 如果新文件不为空,将其保存在filename中
- if (!item.getString().equals(""))
- filename = item.getString("UTF-8");
- }
- }
- // 处理上传文件
- else if (item.getName() != null && !item.getName().equals(""))
- {
- // 从客户端发送过来的上传文件路径中截取文件名
- filename = item.getName().substring(
- item.getName().lastIndexOf("\\") + 1);
- is = item.getInputStream(); // 得到上传文件的InputStream对象
- }
- }
- // 将路径和上传文件名组合成完整的服务端路径
- filename = uploadPath + filename;
- // 如果服务器已经存在和上传文件同名的文件,则输出提示信息
- if (new File(filename).exists())
- {
- new File(filename).delete();
- }
- // 开始上传文件
- if (!filename.equals(""))
- {
- // 用FileOutputStream打开服务端的上传文件
- FileOutputStream fos = new FileOutputStream(filename);
- byte[] buffer = new byte[8192]; // 每次读8K字节
- int count = 0;
- // 开始读取上传文件的字节,并将其输出到服务端的上传文件输出流中
- while ((count = is.read(buffer)) > 0)
- {
- fos.write(buffer, 0, count); // 向服务端文件写入字节流
- }
- fos.close(); // 关闭FileOutputStream对象
- is.close(); // InputStream对象
- out.println("文件上传成功!");
- }
- }
- catch (Exception e)
- {
- }
- }}
********************客户端*****************************
- import java.io.BufferedReader;
- import java.io.DataOutputStream;
- import java.io.FileInputStream;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import android.app.Activity;
- import android.app.AlertDialog;
- import android.content.DialogInterface;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.Button;
- import android.widget.TextView;
- import android.widget.Toast;
- /* import相关class */
- public class EX08_11 extends Activity
- {
- /*
- * 变量声明 filename:上传后在服务器上的文件名称 uploadFile:要上传的文件路径 actionUrl:服务器上对应的程序路径
- */
- private String uploadFile = "/sdcard/notepad/txt/213.txt";
- private String srcPath = "/sdcard/notepad/txt/213.txt";
- private String actionUrl = "http://10.0.2.2:8080/upload_file_service/upload.jsp";
- private TextView mText1;
- private TextView mText2;
- private Button mButton;
- @Override
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- mText1 = (TextView) findViewById(R.id.myText2);
- mText1.setText("文件路径:\n" + uploadFile);
- mText2 = (TextView) findViewById(R.id.myText3);
- mText2.setText("上传网址:\n" + actionUrl);
- /* 设置mButton的onClick事件处理 */
- mButton = (Button) findViewById(R.id.myButton);
- mButton.setOnClickListener(new View.OnClickListener()
- {
- public void onClick(View v)
- {
- uploadFile();
- }
- });
- }
- /* 上传文件至Server的方法 */
- private void uploadFile()
- {
- String uploadUrl = "http://10.0.2.2:8080/upload_file_service/UploadServlet";
- String end = "\r\n";
- String twoHyphens = "--";
- String boundary = "******";
- try
- {
- URL url = new URL(uploadUrl);
- HttpURLConnection httpURLConnection = (HttpURLConnection) url
- .openConnection();
- httpURLConnection.setDoInput(true);
- httpURLConnection.setDoOutput(true);
- httpURLConnection.setUseCaches(false);
- httpURLConnection.setRequestMethod("POST");
- httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
- httpURLConnection.setRequestProperty("Charset", "UTF-8");
- httpURLConnection.setRequestProperty("Content-Type",
- "multipart/form-data;boundary=" + boundary);
- DataOutputStream dos = new DataOutputStream(httpURLConnection
- .getOutputStream());
- dos.writeBytes(twoHyphens + boundary + end);
- dos
- .writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
- + srcPath.substring(srcPath.lastIndexOf("/") + 1)
- + "\"" + end);
- dos.writeBytes(end);
- FileInputStream fis = new FileInputStream(srcPath);
- byte[] buffer = new byte[8192]; // 8k
- int count = 0;
- while ((count = fis.read(buffer)) != -1)
- {
- dos.write(buffer, 0, count);
- }
- fis.close();
- dos.writeBytes(end);
- dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
- dos.flush();
- InputStream is = httpURLConnection.getInputStream();
- InputStreamReader isr = new InputStreamReader(is, "utf-8");
- BufferedReader br = new BufferedReader(isr);
- String result = br.readLine();
- Toast.makeText(this, result, Toast.LENGTH_LONG).show();
- dos.close();
- is.close();
- } catch (Exception e)
- {
- e.printStackTrace();
- setTitle(e.getMessage());
- }
- }
- }