一个简单的安卓+Servlet图片上传例子
来源:互联网 发布:贸仲委待遇怎么样 知乎 编辑:程序博客网 时间:2024/05/23 17:37
例子比较 简单,服务端为Java Web Servlet,doPost方法中接收图片并保存,然后将保存的图片名返回给客户端,关键代码:
@SuppressWarnings("deprecation")public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("utf-8"); //设置编码 //获得磁盘文件条目工厂 DiskFileItemFactory factory = new DiskFileItemFactory(); //获取文件需要上传到的路径 String path = request.getRealPath("/upload"); File file=new File(path); if(!file.exists()){ file.mkdirs(); } factory.setRepository(new File(path)); //设置 缓存的大小 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(path,filename) );//第三方提供的 System.out.println("上传成功:"+filename); response.getWriter().print(filename);//将路径返回给客户端 } } } catch (Exception e) { System.out.println("上传失败"); response.getWriter().print("上传失败:"+e.getMessage()); } }
该方法同样适用于web端即网页图片上传,不是本文重点,不在讲解。
客户端关键代码:
/** * 文件上传 * * @param urlStr 接口路径 * @param filePath 本地图片路径 * @return */public static String formUpload(String urlStr, String filePath) {String rsp = "";HttpURLConnection conn = null;String BOUNDARY = "|"; // request头和上传文件内容分隔符try {URL url = new URL(urlStr);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(filePath);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=\"" + filePath+ "\"; 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;}}return rsp;}
服务端图例:
客户端图例:
注意:测试的时候,请在客户端书写完整的本机局域网IP地址:
/** * 图片上传路径 */public static final String UPLOAD_URL="http://192.168.1.188:8080/uploadImage/UploadServlet";/** * 图片下载路径 */public static final String DOWNLOAD_URL="http://192.168.1.188:8080/uploadImage/upload/";
源码地址:http://download.csdn.net/detail/baiyuliang2013/8714775
1 1
- 一个简单的安卓+Servlet图片上传例子
- Servlet上传的例子
- 一个简单的上传文件测试例子
- 一个jsp和servlet实现上传的例子
- 一个简单jsp-servlet例子
- 一个简单jsp-servlet例子
- 一个简单jsp-servlet例子
- Java简单上传图片例子
- Java简单上传图片例子
- 图片上传(简单例子)
- 一个简单的图片展示例子
- 一个简单的上传录音demo(上传的录音安卓、苹果都可以播放)
- 图片上传的例子
- C# 一个图片上传的简单方法
- 一个简单的上传图片功能
- 一个简单的图片上传预览demo
- 安卓上传图片
- 备忘一下安卓的图片上传
- jQuery日期和时间插件(jquery-ui-timepicker-addon.js)jquerydatapicker插件 实现时分秒
- android开发之Ant多渠到混淆打包
- 求数组的子数组之和的最大值
- mysql中如何判断指定字段的重复数据则不插入?
- 记录一些OFFICE操作技巧
- 一个简单的安卓+Servlet图片上传例子
- 在sql语句多表连接中,in、exists、join那个效率更高一点
- python sqlite3
- SurfaceView 程序效果:用线程画一个蓝色的长方形。
- java操作memcached入门教程demo代码
- 使用Spring进行单元测试
- Ajax总结
- 面试
- 下载以及api地址