android上传图片至服务器

 

 

ByteArrayOutputStream baos = new ByteArrayOutputStream();

Bitmap bm = BitmapFactory.decodeFile(mFileNamePath);

bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);

String photodata = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));

SoapObject request = new SoapObject(NAME_SPACE, METHOD_NAME);

request.addProperty("telno", mPhoneId);

request.addProperty("strbase64", photodata);

SoapSerializationEnvelope envelope = new  SoapSerializationEnvelope(SoapEnvelope.VER11);

new MarshalBase64().register(envelope);

envelope.bodyOut = request;

envelope.dotNet = true;

HttpTransportSE ht = new HttpTransportSE(SERVICE_URL_1);

ht.debug = true;

ht.call(SOAP_ACTION, envelope);

flag = String.valueOf(envelope.getResponse());

 

 

__________________________________________________________________

 

本实例实现了android上传手机图片至服务器,服务器进行保存

服务器servlet代码(需要jar包有:commons-fileupload-1.2.2.jar, commons-io-2.0.1.jar, standard.jar)
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
         public void doGet(HttpServletRequest request, HttpServletResponse response)
                         throws ServletException, IOException {
                 try {
                         System.out.println("IP:" + request.getRemoteAddr());
                         // 1、创建工厂类:DiskFileItemFactory
                         DiskFileItemFactory facotry = new DiskFileItemFactory();
                         String tempDir = getServletContext().getRealPath("/WEB-INF/temp");
                         facotry.setRepository(new File(tempDir));//设置临时文件存放目录
                         // 2、创建核心解析类:ServletFileUpload
                         ServletFileUpload upload = new ServletFileUpload(facotry);
                         upload.setHeaderEncoding("UTF-8");// 解决上传的文件名乱码
                         upload.setFileSizeMax(1024 * 1024 * 1024);// 单个文件上传最大值是1M
                         upload.setSizeMax(2048 * 1024 * 1024);//文件上传的总大小限制
  
                         // 3、判断用户的表单提交方式是不是multipart/form-data
                         boolean bb = upload.isMultipartContent(request);
                         if (!bb) {
                                 return;
                         }
                         // 4、是:解析request对象的正文内容List<FileItem>
                         List<FileItem> items = upload.parseRequest(request);
                         String storePath = getServletContext().getRealPath(
                                         "/WEB-INF/upload");// 上传的文件的存放目录
                         for (FileItem item : items) {
                                 if (item.isFormField()) {
                                         // 5、判断是否是普通表单:打印看看
                                         String fieldName = item.getFieldName();// 请求参数名
                                         String fieldValue = item.getString("UTF-8");// 请求参数值
                                         System.out.println(fieldName + "=" + fieldValue);
                                 } else {
                                         // 6、上传表单:得到输入流,处理上传:保存到服务器的某个目录中
                                         String fileName = item.getName();// 得到上传文件的名称 C:\Documents
                                                                                                                 // and
                                                                                                                 // Settings\shc\桌面\a.txt
                                                                                                                 // a.txt
                                         //解决用户没有选择文件上传的情况
                                         if(fileName==null||fileName.trim().equals("")){
                                                 continue;
                                         }
                                         fileName = fileName
                                                         .substring(fileName.lastIndexOf("\\") + 1);
                                         String newFileName = UUIDUtil.getUUID() + "_" + fileName;
                                         System.out.println("上传的文件名是:" + fileName);
                                         InputStream in = item.getInputStream();
                                         String savePath = makeDir(storePath, fileName) + "\\"
                                                         + newFileName;
                                         OutputStream out = new FileOutputStream(savePath);
                                         byte b[] = new byte[1024];
                                         int len = -1;
                                         while ((len = in.read(b)) != -1) {
                                                 out.write(b, 0, len);
                                         }
                                         in.close();
                                         out.close();
                                         item.delete();//删除临时文件
                                 }
                         }
                 }catch(FileUploadBase.FileSizeLimitExceededException e){
                         request.setAttribute("message", "单个文件大小不能超出5M");
                         request.getRequestDispatcher("/message.jsp").forward(request,
                                         response);
                 }catch(FileUploadBase.SizeLimitExceededException e){
                         request.setAttribute("message", "总文件大小不能超出7M");
                         request.getRequestDispatcher("/message.jsp").forward(request,
                                         response);
         }catch (Exception e) {
                         e.printStackTrace();
                         request.setAttribute("message", "上传失败");
                         request.getRequestDispatcher("/message.jsp").forward(request,
                                         response);
                 }
         }
  
         // WEB-INF/upload/1/3 打散存储目录
         private String makeDir(String storePath, String fileName) {
                 int hashCode = fileName.hashCode();// 得到文件名的hashcode码
                 int dir1 = hashCode & 0xf;// 取hashCode的低4位 0~15
                 int dir2 = (hashCode & 0xf0) >> 4;// 取hashCode的高4位 0~15
                 String path = storePath + "\\" + dir1 + "\\" + dir2;
                 File file = new File(path);
                 if (!file.exists())
                         file.mkdirs();
                 return path;
         }
  
         public void doPost(HttpServletRequest request, HttpServletResponse response)
                         throws ServletException, IOException {
                 doGet(request, response);
         }


UUIDUtil代码如下
代码片段,双击复制
01
02
03
04
05
public class UUIDUtil {
         public static String getUUID(){
                 return UUID.randomUUID().toString();
         }
 }



android客户端代码(需要jar包有:apache-mime4j-0.6.jar,httpmime-4.2.1.jar)
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
public class PhotoUploadActivity extends Activity {
         private String newName = "image.jpg";
         private String uploadFile = "/sdcard/Photo/001.jpg";
         private String actionUrl = "http://10.0.0.144:8080/upload/servlet/UploadServlet";
         private TextView mText1;
         private TextView mText2;
         private Button mButton;
  
         @Override
         public void onCreate(Bundle savedInstanceState) {
                 super.onCreate(savedInstanceState);
                 setContentView(R.layout.photo_upload_activity);
                 mText1 = (TextView) findViewById(R.id.myText1);
                 // "文件路径:\n"+
                 mText1.setText(uploadFile);
                 mText2 = (TextView) findViewById(R.id.myText2);
                 // "上传网址:\n"+
                 mText2.setText(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 end = "\r\n";
                 String twoHyphens = "--";
                 String boundary = "*****";
                 try {
                         URL url = new URL(actionUrl);
                         HttpURLConnection con = (HttpURLConnection) url.openConnection();
                         /* 允许Input、Output,不使用Cache */
                         con.setDoInput(true);
                         con.setDoOutput(true);
                         con.setUseCaches(false);
                         /* 设置传送的method=POST */
                         con.setRequestMethod("POST");
                         /* setRequestProperty */
                         con.setRequestProperty("Connection", "Keep-Alive");
                         con.setRequestProperty("Charset", "UTF-8");
                         con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                         /* 设置DataOutputStream */
                         DataOutputStream ds = new DataOutputStream(con.getOutputStream());
                         ds.writeBytes(twoHyphens + boundary + end);
                         ds.writeBytes("Content-Disposition: form-data; " + "name=\"file1\";filename=\"" + newName + "\"" + end);
                         ds.writeBytes(end);
                         /* 取得文件的FileInputStream */
                         FileInputStream fStream = new FileInputStream(uploadFile);
                         /* 设置每次写入1024bytes */
                         int bufferSize = 1024;
                         byte[] buffer = new byte[bufferSize];
                         int length = -1;
                         /* 从文件读取数据至缓冲区 */
                         while ((length = fStream.read(buffer)) != -1) {
                                 /* 将资料写入DataOutputStream中 */
                                 ds.write(buffer, 0, length);
                         }
                         ds.writeBytes(end);
                         ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
                         /* close streams */
                         fStream.close();
                         ds.flush();
                         /* 取得Response内容 */
                         InputStream is = con.getInputStream();
                         int ch;
                         StringBuffer b = new StringBuffer();
                         while ((ch = is.read()) != -1) {
                                 b.append((char) ch);
                         }
                         /* 将Response显示于Dialog */
                         showDialog("上传成功" + b.toString().trim());
                         /* 关闭DataOutputStream */
                         ds.close();
                 } catch (Exception e) {
                         showDialog("上传失败" + e);
                 }
         }
  
         /* 显示Dialog的method */
         private void showDialog(String mess) {
                 new AlertDialog.Builder(PhotoUploadActivity.this).setTitle("Message").setMessage(mess)
                                 .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                                         public void onClick(DialogInterface dialog, int which) {
                                         }
                                 }).show();
         }
 }




<ignore_js_op>

服务端工程.rar

 

539.07 KB, 下载次数: 237, 下载积分: e币 -2 元

 

web服务器

<ignore_js_op>

Android客户端.rar

 

744.22 KB, 下载次数: 207, 下载积分: e币 -2 元

 

Android客户端工程

posted @ 2013-01-21 09:55  wanqi  阅读(15889)  评论(3编辑  收藏  举报