HttpURLConnection Post请求上传文件和参数到servlet

来源:互联网 发布:太平洋交易软件下载 编辑:程序博客网 时间:2024/06/08 04:58

前台代码:

public String uplaod(String actionUrl, Map<String, String> params) {
        InputStream in = null;
        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";
        URL uri;
        StringBuilder sb2 = null;
        String filePath = params.get("FILE_PATH");
        try {
            uri = new URL(actionUrl);
            HttpURLConnection conn = (HttpURLConnection) uri.openConnection();// 设置从主机读取数据超时
            conn.setReadTimeout(10 * 1000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);

            // 首先组拼文本类型的参数
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(PREFFIX);
                sb.append(BOUNDARY);
                sb.append(LINEND);
                sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
                sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
                sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
                sb.append(LINEND);
                sb.append(entry.getValue());
                sb.append(LINEND);

            }

            DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
            outStream.write(sb.toString().getBytes(CHARSET));

            // 构建发送字符串数据
            if (!ApplicationUtil.isEmptyString(filePath)) { 
                String fileName = params.get("FILE_NAME");
                StringBuilder sb1 = new StringBuilder();
                sb1.append(PREFFIX);
                sb1.append(BOUNDARY);
                sb1.append(LINEND);
                sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"" + LINEND);
                sb1.append("Content-Type: application/octet-stream;chartset=" + CHARSET + LINEND);
                sb1.append(LINEND); 
                // 写入到输出流中
                outStream.write(sb1.toString().getBytes());

                // 将文件读入输入流中
                InputStream is = new FileInputStream(filePath);
                byte[] buffer = new byte[1024];
                int len = 0;
                // 写入输出流
                while ((len = is.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }
                is.close(); // 添加换行标志
                outStream.write(LINEND.getBytes());
            } // 请求结束标志
            byte[] end_data = (PREFFIX + BOUNDARY + PREFFIX + LINEND).getBytes();
            outStream.write(end_data); // 刷新发送数据
            outStream.flush(); // 得到响应码
            int res = conn.getResponseCode();

            // 上传成功返回200
            if (res == 200) {
                in = conn.getInputStream();
                int ch;
                sb2 = new StringBuilder(); // 保存数据
                while ((ch = in.read()) != -1) {
                    sb2.append((char) ch);
                }
            }
            conn.disconnect();
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
        }
        catch (ProtocolException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return sb2 == null ? null : sb2.toString();

    }


后台servlet:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        Map<String,String> params=new HashMap<String,String>();

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            byte[] fileData = null;
            Connection conn = null;
            try {
                Iterator items = upload.parseRequest(request).iterator();
                conn = JdbcUtil.getConnection();
                while (items.hasNext()) {
                    FileItem item = (FileItem) items.next();
                    if (!item.isFormField()) {
                        InputStream in = item.getInputStream();
                        //fileData = IOUtils.toByteArray(in);

//InputStream 
                        ByteArrayOutputStream output = new ByteArrayOutputStream();
                        byte[] buffer = new byte[4096];
                        int n = 0;
                        while (-1 != (n = in.read(buffer))) {
                            output.write(buffer, 0, n);
                        }
                        fileData=output.toByteArray();

                    }
                    else {
                        params.put(item.getFieldName(), item.getString());
                    }
                }

            }
            catch (Exception e2) {
                log.info("error" + e2.getMessage());
            }
        }

    }


1 0
原创粉丝点击