Android HttpURLConnection上传图片至Servlet端指定目录

客户端(核心代码):

/**
 * 文件上传
 *
 * @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;
}

服务端(核心代码):

public class upload extends HttpServlet {

    public upload() {
        super();
    }

    public void destroy() {
        super.destroy();
    }

    /**
     * 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 {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println(
                "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the GET method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * 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
     */
    @SuppressWarnings("deprecation")
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8"); // 设置编码
        // 获得磁盘文件条目工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设定文件需要上传到的路径
        File file = new File("E://WebSite");
        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("E://WebSite", filename));// 第三方提供的
                    System.out.println("上传成功:" + filename);
                    response.getWriter().print(filename);// 将路径返回给客户端
                }
            }
        } catch (Exception e) {
            System.out.println("上传失败");
            e.printStackTrace();
        }
    }

    /**
     * Initialization of the servlet. <br>
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }
}
 

注对于commons-fileupload-1.4.jar和commons-io-1.4.jar而言,不仅仅需要在servlet工程中住进来,还要在本地的Tomcat/lib目录下面进行追加。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android中的HttpURLConnection是一个用于发送和接收HTTP请求的类。它是Java标准库中的一部分,并且在Android开发中被广泛使用。 使用HttpURLConnection可以执行以下操作: 1. 创建连接:使用URL对象创建HttpURLConnection对象,并设置连接的URL。 2. 设置请求方法:使用setRequestMethod()方法设置请求的方法,如GET、POST等。 3. 设置请求头:使用setRequestProperty()方法设置请求头信息,如Content-Type、User-Agent等。 4. 设置请求体:对于POST请求,可以使用OutputStream将数据写入请求体。 5. 发送请求:使用connect()方法建立与服务器的连接,并发送请求。 6. 获取响应码:使用getResponseCode()方法获取服务器的响应码。 7. 获取响应数据:根据响应码,可以使用getInputStream()或getErrorStream()方法获取服务器返回的数据流。 8. 解析响应数据:根据服务器返回的数据格式,可以使用相应的解析方式进行解析,如JSON解析、XML解析等。 以下是一个简单的示例代码,演示了如何使用HttpURLConnection发送GET请求并获取响应数据: ```java try { URL url = new URL("http://www.example.com/api/data"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); connection.disconnect(); // 处理响应数据 String responseData = response.toString(); // ... } else { // 处理错误情况 } } catch (IOException e) { e.printStackTrace(); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值