一个图片上传下载的例子:
1:从相册或者相机选出或拍一张照片
2:裁剪
3:上传到服务器或者从服务器下载
本文最后附带源码
客户端代码:
打开系统自带的相册
Intent intent = new Intent(Intent.ACTION_PICK, null); intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED); startActivityForResult(intent, ALBUM_REQUEST_CODE);
其中 ALBUM_REQUEST_CODE为标识,int类型的变量,随你定
作为后面返回时判断的标识
打开系统自带的相机
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment. getExternalStorageDirectory() + "/temp/", "temp.jpg"))); startActivityForResult(intent, CAMERA_REQUEST_CODE);
拍照或者相册选取完毕之后,开始裁剪
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case ALBUM_REQUEST_CODE: Log.i(TAG, "相册,开始裁剪"); Log.i(TAG, "相册 [ " + data + " ]"); if (data == null) { return; } startCrop(data.getData()); break; case CAMERA_REQUEST_CODE: Log.i(TAG, "相机, 开始裁剪"); File picture = new File(Environment.getExternalStorageDirectory() + "/temp/temp.jpg"); startCrop(Uri.fromFile(picture)); break; case CROP_REQUEST_CODE: Log.i(TAG, "相册裁剪成功"); Log.i(TAG, "裁剪以后 [ " + data + " ]"); if (data == null) { // TODO 如果之前以后有设置过显示之前设置的图片 否则显示默认的图片 return; } Bundle extras = data.getExtras(); if (extras != null) { Bitmap photo = extras.getParcelable("data"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0-100)压缩文件 File fImage = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/temp/testImg.png"); try { fImage.createNewFile(); FileOutputStream iStream = new FileOutputStream(fImage); photo.compress(Bitmap.CompressFormat.PNG, 100, iStream); } catch (Exception e) { e.printStackTrace(); } display.setImageBitmap(photo); //把图片显示在ImageView控件上 } break; default: break; }
裁剪的方法为:
/** * 开始裁剪 */ private void startCrop(Uri uri) { Intent intent = new Intent("com.android.camera.action.CROP");//调用Android系统自带的一个图片剪裁页面, intent.setDataAndType(uri, IMAGE_UNSPECIFIED); intent.putExtra("crop", "true");//进行修剪 // aspectX aspectY 是宽高的比例 intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); // outputX outputY 是裁剪图片宽高 intent.putExtra("outputX", 300); intent.putExtra("outputY", 500); intent.putExtra("return-data", true); startActivityForResult(intent, CROP_REQUEST_CODE); }
上传到服务器:
/** * 上传到服务端 */ private void upLoadToServlet(String temp_path) { HttpURLConnection conn = null; String BOUNDARY = "|"; // request头和上传文件内容分隔符 try { URL url = new URL("http://169.254.186.44:8080/ImageDealWithProject/Test"); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(30000); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); OutputStream out = new DataOutputStream(conn.getOutputStream()); File file = new File(temp_path); String filename = file.getName(); String contentType = ""; if (filename.endsWith(".png")) { contentType = "image/png"; } if (filename.endsWith(".jpg")) { contentType = "image/jpg"; } if (filename.endsWith(".gif")) { contentType = "image/gif"; } if (filename.endsWith(".bmp")) { contentType = "image/bmp"; } if (contentType == null || contentType.equals("")) { contentType = "application/octet-stream"; } StringBuffer strBuf = new StringBuffer(); strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n"); strBuf.append("Content-Disposition: form-data; name=\"" + temp_path + "\"; filename=\"" + filename + "\"\r\n"); strBuf.append("Content-Type:" + contentType + "\r\n\r\n"); out.write(strBuf.toString().getBytes()); DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } in.close(); byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); out.write(endData); out.flush(); out.close(); // 读取返回数据 StringBuffer buffer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); String line = null; while ((line = reader.readLine()) != null) { buffer.append(line).append("\n"); } rsp = buffer.toString(); reader.close(); reader = null; } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); conn = null; } } System.out.println("文件url为:" + rsp); }
从服务器下载:
/** * 保存和显示做完之后直接上传到服务端。 * */ new Thread() { @Override public void run() { upLoadToServlet(Environment.getExternalStorageDirectory().getAbsolutePath() + "/temp/testImg.png"); } }.start();
这里基于方便,直接用了imageloader框架进行加载,
关于imageloader的jar包,本文最后的项目中有,关于具体用法请自行百度。
服务器代码:
服务器就一个servlet。
import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.DiskFileUpload; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class Test extends HttpServlet { /** * Constructor of the object. */ public Test() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to * post. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //将上传到servlet的缓存目录设置到文本下 //之后从android端,就可以直接使用imageLoader来加载 //具体的url地址为:http://ip:8080/ImageDealWithProject//images/filename String uploadDir = request.getSession().getServletContext().getRealPath("/")+ "\\images\\"; System.out.println("有客户端访问"); // 获得磁盘文件条目工厂 DiskFileItemFactory factory = new DiskFileItemFactory(); // 获取文件需要上传到的路径 File file = new File(uploadDir); if (!file.exists()) { file.mkdirs(); } factory.setRepository(file); // 设置 缓存的大小 factory.setSizeThreshold(1024 * 1024); // 文件上传处理 ServletFileUpload upload = new ServletFileUpload(factory); try { // 可以上传多个文件 List<FileItem> list = (List<FileItem>) upload.parseRequest(request); for (FileItem item : list) { // 获取属性名字 String name = item.getFieldName(); // 如果获取的 表单信息是普通的 文本 信息 if (item.isFormField()) { // 获取用户具体输入的字符串,因为表单提交过来的是 字符串类型的 String value = item.getString(); request.setAttribute(name, value); } else { // 获取路径名 String value = item.getName(); // 索引到最后一个反斜杠 int start = value.lastIndexOf("\\"); // 截取 上传文件的 字符串名字,加1是 去掉反斜杠, String filename = value.substring(start + 1); request.setAttribute(name, filename); // 写到磁盘上 item.write(new File(uploadDir, filename));// 第三方提供的 System.out.println("上传成功:" + filename); response.getWriter().print(filename);// 将路径返回给客户端 } } } catch (Exception e) { System.out.println("上传失败"); response.getWriter().print("上传失败:" + e.getMessage()); } } /** * Initialization of the servlet. <br> * * @throws ServletException * if an error occurs */ public void init() throws ServletException { // Put your code here } }
最后说明,代码部分引用多处其他来源,具体情况懒得找,,,
有任何问题可以留言或联系我
546288828
期待共同学习和进步
客户端代码:http://download.csdn.net/detail/qq_26559913/9541456
服务端代码:http://download.csdn.net/detail/qq_26559913/9541455