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客戶端工程


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM