先來客戶端代碼【這裏只寫了主要代碼】
html
先來張效果圖,java
iv_photo.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new ActionSheetDialog(SendGoodsDetailsActivity.this).builder().setTitle("上傳車輛照片") .setCancelable(false).setCanceledOnTouchOutside(false) .addSheetItem("拍照上傳", SheetItemColor.Blue, new OnSheetItemClickListener() { @Override public void onClick(int which) { // 拍照 //設置圖片的保存路徑,做爲全局變量 imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/filename.jpg"; File temp = new File(imageFilePath); Uri imageFileUri = Uri.fromFile(temp);//獲取文件的Uri Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//跳轉到相機Activity it.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);//告訴相機拍攝完畢輸出圖片到指定的Uri startActivityForResult(it, 102); } }).addSheetItem("相冊選擇", SheetItemColor.Blue, new OnSheetItemClickListener() { @Override public void onClick(int which) { // 相冊選取 Intent intent1 = new Intent(Intent.ACTION_GET_CONTENT); intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(intent1, 103); } }).show(); } });
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch(requestCode){ case 102: if (resultCode == Activity.RESULT_OK) { Bitmap bmp = BitmapFactory.decodeFile(imageFilePath); iv_photo.setImageBitmap(bmp); } break; case 103: Bitmap bm = null; // 外界的程序訪問ContentProvider所提供數據 能夠經過ContentResolver接口 ContentResolver resolver = getContentResolver(); try { Uri originalUri = data.getData(); // 得到圖片的uri bm = MediaStore.Images.Media.getBitmap(resolver, originalUri); // 顯獲得bitmap圖片 // 這裏開始的第二部分,獲取圖片的路徑: String[] proj = { MediaStore.Images.Media.DATA }; // 好像是android多媒體數據庫的封裝接口,具體的看Android文檔 @SuppressWarnings("deprecation") Cursor cursor = managedQuery(originalUri, proj, null, null, null); // 按我我的理解 這個是得到用戶選擇的圖片的索引值 int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); // 將光標移至開頭 ,這個很重要,不當心很容易引發越界 cursor.moveToFirst(); // 最後根據索引值獲取圖片路徑 String path = cursor.getString(column_index); iv_photo.setImageURI(originalUri); } catch (IOException e) { e.printStackTrace(); } break; } super.onActivityResult(requestCode,resultCode,data); }
下面是上傳的一個工具類,嘻嘻,從網上找的一個大神的,能夠用android
/** * * 上傳工具類 * @author spring sky * Email:vipa1888@163.com * QQ:840950105 * MyName:石明政 */ public class UploadUtil { private static final String TAG = "uploadFile"; private static final int TIME_OUT = 10*1000; //超時時間 private static final String CHARSET = "utf-8"; //設置編碼 /** * android上傳文件到服務器 * @param file 須要上傳的文件 * @param RequestURL 請求的rul * @return 返回響應的內容 */ public static String uploadFile(File file,String RequestURL){ String result = null; String BOUNDARY = UUID.randomUUID().toString(); //邊界標識 隨機生成 String PREFIX = "--" , LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; //內容類型 try { URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); conn.setDoInput(true); //容許輸入流 conn.setDoOutput(true); //容許輸出流 conn.setUseCaches(false); //不容許使用緩存 conn.setRequestMethod("POST"); //請求方式 conn.setRequestProperty("Charset", CHARSET); //設置編碼 conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); conn.connect(); if(file!=null){ /** * 當文件不爲空,把文件包裝而且上傳 */ DataOutputStream dos = new DataOutputStream( conn.getOutputStream()); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * 這裏重點注意: * name裏面的值爲服務器端須要key 只有這個key 才能夠獲得對應的文件 * filename是文件的名字,包含後綴名的 好比:abc.png */ sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END); sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); InputStream is = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = 0; while((len=is.read(bytes))!=-1){ dos.write(bytes, 0, len); } is.close(); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes(); dos.write(end_data); dos.flush(); /** * 獲取響應碼 200=成功 * 當響應成功,獲取響應的流 */ int res = conn.getResponseCode(); if(res==200){ InputStream input = conn.getInputStream(); StringBuffer sb1= new StringBuffer(); int ss ; while((ss=input.read())!=-1){ sb1.append((char)ss); } result = sb1.toString(); System.out.println(result); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } }
在下就是調用上傳的方法了,這裏我給摘出來了spring
File file = new File(path); //這裏的path就是那個地址的全局變量 String result = UploadUtil.uploadFile(file, RequestURL);
這裏客戶端就完成了,下面就是服務端代碼,這裏我用的是servlet
數據庫
public class UploadShipServlet extends HttpServlet { private static final long serialVersionUID = 1L; private String path; public UploadShipServlet() { super(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); // 建立文件項目工廠對象 DiskFileItemFactory factory = new DiskFileItemFactory(); // 設置文件上傳路徑 String upload = this.getServletContext().getRealPath("/"); // 獲取系統默認的臨時文件保存路徑,該路徑爲Tomcat根目錄下的temp文件夾 String temp = System.getProperty("java.io.tmpdir"); // 設置緩衝區大小爲 5M factory.setSizeThreshold(1024 * 1024 * 5); // 設置臨時文件夾爲temp factory.setRepository(new File(temp)); // 用工廠實例化上傳組件,ServletFileUpload 用來解析文件上傳請求 ServletFileUpload servletFileUpload = new ServletFileUpload(factory); // 解析結果放在List中 try { List<FileItem> list = servletFileUpload.parseRequest(request); for (FileItem item : list) { String name = item.getFieldName(); InputStream is = item.getInputStream(); if (name.contains("content")) { System.out.println(inputStream2String(is)); } else if (name.contains("img")) { try { path = upload+"\\"+item.getName(); inputStream2File(is, path); break; } catch (Exception e) { e.printStackTrace(); } } } out.write(path); //這裏我把服務端成功後,返回給客戶端的是上傳成功後路徑 } catch (FileUploadException e) { e.printStackTrace(); System.out.println("failure"); out.write("failure"); } out.flush(); out.close(); } // 流轉化成字符串 public static String inputStream2String(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int i = -1; while ((i = is.read()) != -1) { baos.write(i); } return baos.toString(); } // 流轉化成文件 public static void inputStream2File(InputStream is, String savePath) throws Exception { System.out.println("文件保存路徑爲:" + savePath); File file = new File(savePath); InputStream inputSteam = is; BufferedInputStream fis = new BufferedInputStream(inputSteam); FileOutputStream fos = new FileOutputStream(file); int f; while ((f = fis.read()) != -1) { fos.write(f); } fos.flush(); fos.close(); fis.close(); inputSteam.close(); } }
ok了,這樣就大功告成了,多整理之後好用得着。
緩存