例子比较 简单,服务端为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

一个简单的安卓+Servlet图片上传例子的更多相关文章

  1. ASP.NET Core 简单实现七牛图片上传(FormData 和 Base64)

    ASP.NET Core 简单实现七牛图片上传(FormData 和 Base64) 七牛图片上传 SDK(.NET 版本):https://developer.qiniu.com/kodo/sdk/ ...

  2. Java Servlet图片上传至指定文件夹并显示图片

    在学习Servlet过程中,针对图片上传做了一个Demo,实现的功能是:在a页面上传图片,点击提交后,将图片保存到服务器指定路径(D:/image):跳转到b页面,b页面读取展示绝对路径(D:/ima ...

  3. 简单的Django实现图片上传,并存储进MySQL数据库 案例——小白

    目标:通过网页上传一张图片到Django后台,后台接收并存储进数据库 真是不容易!!这个案例的代码网上太乱,不适合我,自己摸索着写,终于成功了,记录一下,仅供自己参考,有的解释可能不对,自己明白就好, ...

  4. Servlet图片上传

    package com.servlet; import java.io.DataInputStream; import java.io.FileOutputStream; import java.io ...

  5. ___简单的MVC单个图片上传预览

    js: $("#btnImg").click(function () { $("#form0").ajaxSubmit({ url: "/Studen ...

  6. 简单实现的Servlet文件上传,并显示

    http://my.oschina.net/Barudisshu/blog/157481

  7. UEditor之实现配置简单的图片上传示例

    UEditor之实现配置简单的图片上传示例 原创 2016年06月11日 18:27:31 开心一笑 下班后,阿华到楼下小超市买毛巾,刚买完出来,就遇到同一办公楼里另一家公司的阿菲,之前与她远远的有过 ...

  8. angularJS+Ionic移动端图片上传的解决办法

    前端开发中经常会碰到图片上传的问题,网上的解决办法很多,可是有些图片上传的插件会有一些附属的插件,因此因为一个图片上传的问题可能额需要引入其他插件到项目中,久而久之项目会不伦不类,有时候插件之间也会有 ...

  9. Asp.Net Core Web Api图片上传(一)集成MongoDB存储实例教程

    Asp.Net Core Web Api图片上传及MongoDB存储实例教程(一) 图片或者文件上传相信大家在开发中应该都会用到吧,有的时候还要对图片生成缩略图.那么如何在Asp.Net Core W ...

随机推荐

  1. 【codevs 1911 孤岛营救问题】

    ·为了分析方便,可以先做一个题目简化.去掉"钥匙"这个条件,那么就是一个BFS或者SPFA--现在加上该条件.如本题只给出最多两种钥匙,当然你可以继续坚持BFS等方式,时间不会太差 ...

  2. 习题9-6 uva 10723

    题意: 给你两个字符串,求一个最短的串,使得输入的两个串均是他的子序列(不一定连续) 思路: 可以看出ans = 两个串的长度和 - 两个串的最长公共子序列,在最后的构造处GG.  在构造时想了很久, ...

  3. Miller-Rabin,Pollard-Rho(BZOJ3667)

    裸题直接做就好了. #include <cstdio> #include <cstdlib> #include <algorithm> using namespac ...

  4. Linux配置服务器的一点总结

    一.Linux初始化服务 首先搞清楚四个概念: 进程:正在运行的程序,有自己独立的内存空间. 线程:是进程的下属单位,开销较进程小,没有自己独立的内存空间. 作业:由一系列进程组成,来完成某一项任务. ...

  5. Machine Learning From Scratch-从头开始机器学习

    Python implementations of some of the fundamental Machine Learning models and algorithms from scratc ...

  6. jquery easyui panel title文字格式设置

    $('#txtLeftPercent').panel({ title: '剩余权重:' + '<b style="color:red">' + 100 + '%< ...

  7. 程序包org.junit不存在

    三种解决方法 第一种 maven的改法 <dependency>            <groupId>junit</groupId>            &l ...

  8. php闭包类外操作私有属性

    Closure::bind() Closure::bindTo(); class person{ private $age; private $sex; public function __const ...

  9. ubuntu14.04 安装PIL库出现OError: decoder jpeg not available 的解决方案

    出现 OError: decoder jpeg not available 的原因是,没有装JPEG的库,同时要支持png图片的话还要装 ZLIB.FREETYPE2.LITTLECMS的库文件. 先 ...

  10. JAVA中抽象类的使用

    抽象类是从多个具体类中抽象出来的父类,它具有更高层次的抽象.抽象类体现的就是一种模板模式的设计,抽象父类可以只定义需要使用的某些方法,把不能实现的某些部分抽象成抽象方法,留给其子类去实现.具体来说,抽 ...