安卓上传文件到服务器源码 - 云代码

时间:2021-09-04 14:28:46

完整源码:http://yuncode.net/code/c_5063ece6eba2d94

 

 

客户端
 
001 package com.example.testandroid;
002   
003 import java.io.DataOutputStream;
004 import java.io.FileInputStream;
005 import java.io.InputStream;
006 import java.net.HttpURLConnection;
007 import java.net.URL;
008   
009 import android.app.Activity;
010 import android.app.AlertDialog;
011 import android.content.DialogInterface;
012 import android.os.Bundle;
013 import android.view.View;
014 import android.widget.Button;
015 import android.widget.TextView;
016   
017 public class PhotoUpload extendsActivity {
018     privateString newName = "image.jpg";
019     privateString uploadFile = "/sdcard/image.JPG";// 要上传的文件
020     privateString actionUrl = "http://192.168.0.1:8080/PhotoUpload/servlet/UploadServlet";
021     privateTextView mText1;
022     privateTextView mText2;
023     privateButton mButton;
024   
025     @Override
026     publicvoid onCreate(Bundle savedInstanceState) {
027         super.onCreate(savedInstanceState);
028         setContentView(R.layout.activity_main);
029         mText1 = (TextView) findViewById(R.id.myText2);
030         // 文件路径:
031         mText1.setText(uploadFile);
032         mText2 = (TextView) findViewById(R.id.myText3);
033         // 上传网址:
034         mText2.setText(actionUrl);
035         /* 设置mButton的onClick事件处理 */
036         mButton = (Button) findViewById(R.id.myButton);
037         mButton.setOnClickListener(newView.OnClickListener() {
038             publicvoid onClick(View v) {
039                 uploadFile();
040             }
041         });
042     }
043   
044     /* 上传文件至Server的方法 */
045     privatevoid uploadFile() {
046         String end ="\r\n";
047         String twoHyphens ="--";
048         String boundary ="*****";
049         try{
050             URL url =new URL(actionUrl);
051             HttpURLConnection con = (HttpURLConnection) url.openConnection();
052             /* 允许Input、Output,不使用Cache */
053             con.setDoInput(true);
054             con.setDoOutput(true);
055             con.setUseCaches(false);
056   
057             // 设置http连接属性
058             con.setRequestMethod("POST");
059             con.setRequestProperty("Connection","Keep-Alive");
060             con.setRequestProperty("Charset","UTF-8");
061             con.setRequestProperty("Content-Type",
062                     "multipart/form-data;boundary="+ boundary);
063   
064             DataOutputStream ds =new DataOutputStream(con.getOutputStream());
065             ds.writeBytes(twoHyphens + boundary + end);
066             ds.writeBytes("Content-Disposition: form-data; "
067                     +"name=\"file1\";filename=\"" + newName + "\"" + end);
068             ds.writeBytes(end);
069   
070             // 取得文件的FileInputStream
071             FileInputStream fStream =new FileInputStream(uploadFile);
072             /* 设置每次写入1024bytes */
073             intbufferSize = 1024;
074             byte[] buffer =new byte[bufferSize];
075             intlength = -1;
076             /* 从文件读取数据至缓冲区 */
077             while((length = fStream.read(buffer)) != -1) {
078                 /* 将资料写入DataOutputStream中 */
079                 ds.write(buffer,0, length);
080             }
081             ds.writeBytes(end);
082             ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
083   
084             fStream.close();
085             ds.flush();
086             /* 取得Response内容 */
087             InputStream is = con.getInputStream();
088             intch;
089             StringBuffer b =new StringBuffer();
090             while((ch = is.read()) != -1) {
091                 b.append((char) ch);
092             }
093             /* 将Response显示于Dialog */
094             showDialog("上传成功"+ b.toString().trim());
095             /* 关闭DataOutputStream */
096             ds.close();
097         }catch (Exception e) {
098             showDialog("上传失败"+ e);
099         }
100     }
101   
102     /* 显示Dialog的method */
103     privatevoid showDialog(String mess) {
104         newAlertDialog.Builder(PhotoUpload.this).setTitle("Message")
105                 .setMessage(mess)
106                 .setNegativeButton("确定",new DialogInterface.OnClickListener() {
107                     publicvoid onClick(DialogInterface dialog,int which) {
108                     }
109                 }).show();
110     }
111 }


服务器端  
01 package com.demo;
02   
03 import java.io.File;
04 import java.io.IOException;
05 import java.util.Date;
06 import java.util.Iterator;
07 import java.util.List;
08   
09 import javax.servlet.ServletException;
10 import javax.servlet.http.HttpServlet;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13   
14 import org.apache.commons.fileupload.DiskFileUpload;
15 import org.apache.commons.fileupload.FileItem;
16   
17 public class UploadServlet extendsHttpServlet {
18     publicvoid doPost(HttpServletRequest request, HttpServletResponse response)
19             throwsServletException, IOException {
20   
21         String temp = request.getSession().getServletContext().getRealPath("/")
22                 +"temp"; // 临时目录
23         System.out.println("temp="+ temp);
24         String loadpath = request.getSession().getServletContext()
25                 .getRealPath("/")
26                 +"Image"; // 上传文件存放目录
27         System.out.println("loadpath="+ loadpath);
28         DiskFileUpload fu =new DiskFileUpload();// 需要导入commons-fileupload-1.2.2.jar
29                                                     //http://commons.apache.org/fileupload/
30         fu.setSizeMax(1* 1024 * 1024); // 设置允许用户上传文件大小,单位:字节
31         fu.setSizeThreshold(4096);// 设置最多只允许在内存中存储的数据,单位:字节
32         fu.setRepositoryPath(temp);// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
33   
34         // 开始读取上传信息
35         intindex = 0;
36         List fileItems =null;
37   
38         try{
39             fileItems = fu.parseRequest(request);
40             System.out.println("fileItems="+ fileItems);
41         }catch (Exception e) {
42             e.printStackTrace();
43         }
44   
45         Iterator iter = fileItems.iterator();// 依次处理每个上传的文件
46         while(iter.hasNext()) {
47             FileItem item = (FileItem) iter.next();// 忽略其他不是文件域的所有表单信息
48             if(!item.isFormField()) {
49                 String name = item.getName();// 获取上传文件名,包括路径
50                 name = name.substring(name.lastIndexOf("\\") +1);// 从全路径中提取文件名
51                 longsize = item.getSize();
52                 if((name == null || name.equals("")) && size ==0)
53                     continue;
54                 intpoint = name.indexOf(".");
55                 name = (newDate()).getTime()
56                         + name.substring(point, name.length()) + index;
57                 index++;
58                 File fNew =new File(loadpath, name);
59                 try{
60                     item.write(fNew);
61                 }catch (Exception e) {
62                     // TODO Auto-generated catch block
63                     e.printStackTrace();
64                 }
65   
66             }else// 取出不是文件域的所有表单信息
67             {
68                 String fieldvalue = item.getString();
69                 // 如果包含中文应写为:(转为UTF-8编码)
70                 // String fieldvalue = new
71                 // String(item.getString().getBytes(),"UTF-8");
72             }
73         }
74         String text1 ="11";
75         response.sendRedirect("result.jsp?text1="+ text1);
76     }
77 }