首先是上傳的 PostFile
[java]
1. //上傳代碼,第一個參數,為要使用的URL,第二個參數,為表單內容,第三個參數為要上傳的文件,可以上傳多個文件,這根據需要頁定
2. private static final String TAG = "uploadFile";
3. private static final int TIME_OUT = 10*1000; //超時時間
4. private static final String CHARSET = "utf-8"; //設置編碼
5. /**
6. * android上傳文件到服務器
7. * @param file 需要上傳的文件
8. * @param RequestURL 請求的rul
9. * @return 返回響應的內容
10. */
11. public static String uploadFile(File file,String RequestURL)
12. {
13. String result = null;
14. String BOUNDARY = UUID.randomUUID().toString(); //邊界標識 隨機生成
15. String PREFIX = "–" , LINE_END = "\r\n";
16. String CONTENT_TYPE = "multipart/form-data"; //內容類型
17.
18. try {
19. URL url = new URL(RequestURL);
20. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
21. conn.setReadTimeout(TIME_OUT);
22. conn.setConnectTimeout(TIME_OUT);
23. conn.setDoInput(true); //允許輸入流
24. conn.setDoOutput(true); //允許輸出流
25. conn.setUseCaches(false); //不允許使用緩存
26. conn.setRequestMethod("POST"); //請求方式
27. conn.setRequestProperty("Charset", CHARSET); //設置編碼
28. conn.setRequestProperty("connection", "keep-alive");
29. conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
30.
31. if(file!=null)
32. {
33. /**
34. * 當文件不為空,把文件包裝並且上傳
35. */
36. DataOutputStream dos = new DataOutputStream( conn.getOutputStream());
37. StringBuffer sb = new StringBuffer();
38. sb.append(PREFIX);
39. sb.append(BOUNDARY);
40. sb.append(LINE_END);
41. /**
42. * 這裡重點註意:
43. * name裡面的值為服務器端需要key 隻有這個key 才可以得到對應的文件
44. * filename是文件的名字,包含後綴名的 比如:abc.png
45. */
46. sb.append("Content-Disposition: form-data; name=\"fup\"; filename=\""+file.getName()+"\""+LINE_END);
47. sb.append("Content-Type: image/pjpeg; charset="+CHARSET+LINE_END);
48. sb.append(LINE_END);
49. dos.write(sb.toString().getBytes());
50. InputStream is = new FileInputStream(file);
51. byte[] bytes = new byte[1024];
52. int len = 0;
53. while((len=is.read(bytes))!=-1)
54. {
55. dos.write(bytes, 0, len);
56. }
57. is.close();
58. dos.write(LINE_END.getBytes());
59. byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
60. dos.write(end_data);
61. dos.flush();
62. /**
63. * 獲取響應碼 200=成功
64. * 當響應成功,獲取響應的流
65. */
66. int res = conn.getResponseCode();
67. Log.i(TAG, "response code:"+res);
68. if(res==200)
69. {
70. Log.e(TAG, "request success");
71. InputStream input = conn.getInputStream();
72. StringBuffer sb1= new StringBuffer();
73. int ss ;
74. while((ss=input.read())!=-1)
75. {
76. sb1.append((char)ss);
77. }
78. result = sb1.toString();
79. Log.i(TAG, "result : "+ result);
80. }
81. else{
82. Log.i(TAG, "request error");
83. }
84. }
85. } catch (MalformedURLException e) {
86. e.printStackTrace();
87. } catch (IOException e) {
88. e.printStackTrace();
89. }
90. return result;
91. }
這個方法需要傳遞一個由圖片的path(路徑)生成的file格式的數據。和上傳地址的url。
首先是本地上傳。
[java]
1. /***
2. * 這個是調用android內置的intent,來過濾圖片文件 ,同時也可以過濾其他的
3. */
4. Intent intent = new Intent();
5. intent.setType("image/*");
6. intent.setAction(Intent.ACTION_GET_CONTENT);
7. startActivityForResult(intent, selectCode);
這個是調用本地圖片庫。
返回過後是在 ResultActivty裡返回。
[java]
1. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
2. super.onActivityResult(requestCode, resultCode, data);
3. if(selectCode==requestCode){
4. /**
5. * 當選擇的圖片不為空的話,在獲取到圖片的途徑
6. */
7. Uri uri = data.getData();
8. Log.i(TAG, "uri = "+ uri);
9. try {
10. String[] pojo = {MediaStore.Images.Media.DATA};
11. Cursor cursor = managedQuery(uri, pojo, null, null,null);
12. if(cursor!=null)
13. {
14. ContentResolver cr = this.getContentResolver();
15. int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
16. cursor.moveToFirst();
17. String path = cursor.getString(colunm_index);
18. /***
19. * 這裡加這樣一個判斷主要是為瞭第三方的軟件選擇,比如:使用第三方的文件管理器的話,你選擇的文件就不一定是圖片瞭,這樣的話,我們判斷文件的後綴名
20. * 如果是圖片格式的話,那麼才可以
21. */
22. if(path.endsWith("jpg")||path.endsWith("png"))
23. {
24. picPath = path;
25. Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
26. imageView.setImageBitmap(bitmap);
27. }else{alert();}
28. }else{alert();}
29.
30. } catch (Exception e) {
31.
32. }
33. super.onActivityResult(requestCode, resultCode, data);
34. }
取值,並且將圖片填充到imageView裡。本Activty裡全局變量保存picPath。
拍照上傳,首先要進入照相機。
[java]
1. destoryBimap();
2. String state = Environment.getExternalStorageState();
3. if (state.equals(Environment.MEDIA_MOUNTED)) {
4. intent = new Intent("android.media.action.IMAGE_CAPTURE");
5. startActivityForResult(intent, cameraCode);
6. } else {
7. Toast.makeText(SsActivity.this,"請插入SD卡", Toast.LENGTH_LONG).show();
8. }
9. break;
判斷有沒有SD卡。沒有就提示插入SD卡。接受返回值任然實在ResultActivity
[java]
1. if(cameraCode==requestCode){
2. Bundle bundle = data.getExtras();
3. photo= (Bitmap) bundle.get("data");// 獲取相機返回的數據,並轉換為Bitmap圖片格式
4. ByteArrayOutputStream baos = new ByteArrayOutputStream();
5. photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 把數據寫入文件
6. Uri uri = data.getData();
7. Log.i(TAG, "uri = "+ uri);
8. try {
9. String[] pojo = {MediaStore.Images.Media.DATA};
10. Cursor cursor = managedQuery(uri, pojo, null, null,null);
11. if(cursor!=null){
12. int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
13. cursor.moveToFirst();
14. String path = cursor.getString(colunm_index);
15. if(path!=null){
16. picPath=path;
17. imageView.setImageBitmap(photo);
18. }
19. }
20. }catch (Exception e) {
21. // TODO: handle exception
22. }
23. }
此返回值跟上面本地取圖片一樣。返回picPath,並且將圖片填充至imageView。
上傳:
[java]
1. File file = new File(saveBefore(picPath));
2. if(file!=null)
3. {
4. String request = PostFile.uploadFile( file, requestURL);
5. uploadImage.setText(request);
6. }
7. break;
上傳之前將圖片壓縮。
現在附上一些轉換方法
[java]
1. private void destoryBimap() {
2. if (photo != null && !photo.isRecycled()) {
3. photo.recycle();
4. photo = null;
5. }
6. }
[java]
1. /**
2. * 讀取路徑中的圖片,然後將其轉化為縮放後的bitmap
3. * @param path
4. */
5. public String saveBefore(String path) {
6. BitmapFactory.Options options = new BitmapFactory.Options();
7. options.inJustDecodeBounds = true;
8. // 獲取這個圖片的寬和高
9. Bitmap bitmap = BitmapFactory.decodeFile(path, options); // 此時返回bm為空
10. options.inJustDecodeBounds = false;
11. // 計算縮放比
12. int be = (int) (options.outHeight / (float) 200);
13. if (be <= 0)
14. be = 1;
15. options.inSampleSize = 4; // 圖片長寬各縮小至四分之一
16. // 重新讀入圖片,註意這次要把options.inJustDecodeBounds 設為 false哦
17. bitmap = BitmapFactory.decodeFile(path, options);
18. // savePNG_After(bitmap,path);
19. return saveJPGE_After(bitmap, path);
20. }
21. /**
22. * 保存圖片為JPEG
23. * @param bitmap
24. * @param path
25. */
26. public String saveJPGE_After(Bitmap bitmap, String path) {
27. File file = new File(path);
28. try {
29. FileOutputStream out = new FileOutputStream(file);
30. if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
31. out.flush(); www.aiwalls.com
32. out.close();
33. }
34. } catch (FileNotFoundException e) {
35. e.printStackTrace();
36. } catch (IOException e) {
37. e.printStackTrace();
38. }
39. return path;
40. }
作者:lb454048898