先来客户端代码【这里只写了主要代码】
先来张效果图,
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); }
下面是上传的一个工具类,嘻嘻,从网上找的一个大神的,可以用
/** * * 上传工具类 * @author spring sky * Email:[email protected] * 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; } }
在下就是调用上传的方法了,这里我给摘出来了
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了,这样就大功告成了,多整理以后好用得着。