Android+Servlet图片上传 (Tomcat+jsp)

之前学习servlet的时候用到过,今天偶然又翻到了那位大神的博客,就来转载记录一下。

例子比较 简单,服务端为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 list = (List)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;
    }

服务端图例:
Android+Servlet图片上传 (Tomcat+jsp)_第1张图片

客户端图例:
Android+Servlet图片上传 (Tomcat+jsp)_第2张图片

Android+Servlet图片上传 (Tomcat+jsp)_第3张图片

注意:测试的时候,请在客户端书写完整的本机局域网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
感谢:http://www.bkjia.com/Androidjc/1002132.html

你可能感兴趣的:(无聊)