Android本地选择图片显示并上传(客户端+服务器)
2016-09-29 16:04
423 查看
自己写的一个小例子,还没有测试,仅供参考
安卓客户端
MainActivity.java
工具类
UploadUtil.java
布局文件
activity_main.xml
服务器端
AndroidServlet.java
配置文件
web.xml
页面
result.jsp
谢谢大家!
安卓客户端
MainActivity.java
import java.io.File; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ContentResolver; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener { private static String requestURL = "http://localhost:9999/Struts_Study/UploadFileServlet"; private Button selectImage, uploadImage; private ImageView imageView; private String picPath = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); selectImage = (Button) this.findViewById(R.id.selectImage); uploadImage = (Button) this.findViewById(R.id.uploadImage); selectImage.setOnClickListener(this); uploadImage.setOnClickListener(this); imageView = (ImageView) this.findViewById(R.id.imageView); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.selectImage: /*** * 这个是调用android内置的intent,来过滤图片文件 ,同时也可以过滤其他的 */ Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent, 1); break; case R.id.uploadImage: if (picPath == null) { Toast.makeText(MainActivity.this, "请选择图片!", 1000).show(); } else { final File file = new File(picPath); if (file != null) { int request = UploadUtil.uploadFile(file, requestURL); uploadImage.setText(request); } } break; default: break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { /** * 当选择的图片不为空的话,在获取到图片的途径 */ Uri uri = data.getData(); Log.e("tag", "uri = " + uri); try { String[] pojo = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(uri, pojo, null, null, null); if (cursor != null) { ContentResolver cr = this.getContentResolver(); int colunm_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String path = cursor.getString(colunm_index); /*** * * 这里加这样一个判断主要是为了第三方的软件选择,比如:使用第三方的文件管理器的话,你选择的文件就不一定是图片了, * * 这样的话,我们判断文件的后缀名 如果是图片格式的话,那么才可以 */ if (path.endsWith("jpg") || path.endsWith("png")) { picPath = path; Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri)); imageView.setImageBitmap(bitmap); } else { alert(); } } else { alert(); } } catch (Exception e) { } } super.onActivityResult(requestCode, resultCode, data); } private void alert() { Dialog dialog = new AlertDialog.Builder(this).setTitle("提示") .setMessage("您选择的不是有效的图片") .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { picPath = null; } }).create(); dialog.show(); } }
工具类
UploadUtil.java
import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.UUID; import android.util.Log; public class UploadUtil { private static final String TAG = "uploadFile"; private static final int TIME_OUT = 10 * 1000; // 超时时间 private static final String CHARSET = "utf-8"; // 设置编码 /** * 上传文件到服务器 * @param file 需要上传的文件 * @param RequestURL 请求的rul * @return 返回响应的内容 */ public static int uploadFile(File file, String RequestURL) { int res=0; 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); 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是文件的名字,包含后缀名 */ sb.append("Content-Disposition: form-data; name=\"file\"; 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=成功 当响应成功,获取响应的流 * */ res = conn.getResponseCode(); Log.e(TAG, "response code:" + res); if (res == 200) { Log.e(TAG, "request success"); InputStream input = conn.getInputStream(); StringBuffer sb1 = new StringBuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.toString(); Log.e(TAG, "result : " + result); } else { Log.e(TAG, "request error"); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return res; } }
布局文件
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context="com.yanglic.imageupload.MainActivity" > <Button android:id="@+id/selectImage" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="选择图片" /> <Button android:id="@+id/uploadImage" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="上传图片" /> <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
服务器端
AndroidServlet.java
import java.io.File; import java.io.IOException; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.DiskFileUpload; import org.apache.tomcat.util.http.fileupload.FileItem; public class AndroidServlet { public void doPost(HttpServletRequest request, a8a4 HttpServletResponse response) throws ServletException, IOException { String temp = request.getSession().getServletContext().getRealPath("/") + "temp"; // 临时目录 System.out.println("temp=" + temp); String loadpath = request.getSession().getServletContext() .getRealPath("/") + "Image"; // 上传文件存放目录 System.out.println("loadpath=" + loadpath); DiskFileUpload fu = new DiskFileUpload(); fu.setSizeMax(1 * 1024 * 1024); // 设置允许用户上传文件大小,单位:字节 fu.setSizeThreshold(4096); // 设置最多只允许在内存中存储的数据,单位:字节 fu.setRepositoryPath(temp); // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录 // 开始读取上传信息 int index = 0; List fileItems = null; try { fileItems = fu.parseRequest(request); System.out.println("fileItems=" + fileItems); } catch (Exception e) { e.printStackTrace(); } Iterator iter = fileItems.iterator(); // 依次处理每个上传的文件 while (iter.hasNext()) { FileItem item = (FileItem) iter.next();// 忽略其他不是文件域的所有表单信息 if (!item.isFormField()) { String name = item.getName();// 获取上传文件名,包括路径 name = name.substring(name.lastIndexOf("\\") + 1);// 从全路径中提取文件名 long size = item.getSize(); if ((name == null || name.equals("")) && size == 0) continue; int point = name.indexOf("."); name = (new Date()).getTime() + name.substring(point, name.length()) + index; index++; File fNew = new File(loadpath, name); try { item.write(fNew); } catch (Exception e) { e.printStackTrace(); } } else// 取出不是文件域的所有表单信息 { String fieldvalue = item.getString(); // 如果包含中文应写为:(转为UTF-8编码) // String fieldvalue = new // String(item.getString().getBytes(),"UTF-8"); } } String text1 = "11"; response.sendRedirect("result.jsp?text1=" + text1); } }
配置文件
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>UploadFileServlet</servlet-name> <servlet-class>com.yanglic.action.AndroidServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadFileServlet</servlet-name> <url-pattern>/UploadFileServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>result.jsp</welcome-file> </welcome-file-list> </web-app>
页面
result.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <html> <head> <base href="<%=basePath%>"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 安卓服务器测试页面 </body> </html>
谢谢大家!
相关文章推荐
- android 客户端通过选择本地相册和拍照上传本地图片到服务器端
- android选择图片或拍照图片上传到服务器(包括上传参数)
- android选择图片或拍照图片上传到服务器(包括上传参数)
- android拍照选择图片上传服务器自定义控件
- android-ImageView显示选择本地图片或拍照
- Android-ImageView显示选择本地图片或拍照
- android拍照选择图片上传服务器自定义控件
- android选择图片或拍照图片上传到服务器(包括上传参数)
- android选择图片或拍照图片上传到服务器(包括上传参数)
- android 开启本地相册选择图片并返回显示
- android选择图片或拍照图片上传到服务器(包括上传参数)
- android从本地媒体库获取图片上传至服务器保存
- android选择图片或拍照图片上传到服务器(包括上传参数)
- android选择图片或拍照图片上传到服务器(包括上传参数)
- android选择图片或拍照图片上传到服务器(包括上传参数)
- android-显示选择本地图片或拍照
- android选择图片或拍照图片上传到服务器(包括上传参数)
- Android 拍照 以及从本地选择图片 上传
- android选择图片或拍照图片上传到服务器(包括上传参数)
- android选择图片或拍照图片上传到服务器(包括上传参数)