java - 使用httpclient4.3.1 上传文件的同时添加普通参数,服务端取不到参数

 mobiledu2502860643 发布于 2022-10-30 21:18

javax.servlet
javax.servlet-api
3.0.1
provided


org.apache.httpcomponents  
httpclient  
4.3.1  

org.apache.httpcomponents  
httpcore  
4.3.1  


org.apache.httpcomponents  
httpmime  
4.3.1  

commons-fileupload
commons-fileupload
1.3.2

客户端

    // 创建默认的httpClient实例.
    HttpClient httpclient = HttpClients.createDefault();
    // 创建httppost
    HttpPost httppost = new HttpPost(UploadService);
    // 创建参数队列
    FileBody bin = new FileBody(new File("D:\\download\\1.jpg"));
    // StringBody pathBody = new
    // StringBody("/20170317/",ContentType.DEFAULT_TEXT);

    HttpEntity reqEntity = MultipartEntityBuilder.create()
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addBinaryBody("uploadFile", new File("D:\\download\\1.jpg"))
            .addTextBody("path", "/20170317/").build();
    try {
        httppost.setEntity(reqEntity);
        System.out.println("executing request " + httppost.getURI());
        HttpResponse response = httpclient.execute(httppost);
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                System.out
                        .println("--------------------------------------");
                System.out.println("Response content: "
                        + EntityUtils.toString(entity, "UTF-8"));
                System.out
                        .println("--------------------------------------");
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        }
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

服务端

    try {  
        System.out.println("IP:" + request.getRemoteAddr());  
        String path= request.getParameter("path");
        Part part1=  request.getPart("path");
        Iteratoriterator=request.getParts().iterator();  
        
        while (iterator.hasNext()) {//遍历客户端上传的所有文件                
            Part part = (Part) iterator.next();   
            System.out.println(part.getContentType());
        }  
        String username =request.getParameter("username");
        System.out.println("username:" + username);
        // 1、创建工厂类:DiskFileItemFactory  
        DiskFileItemFactory facotry = new DiskFileItemFactory();  
        String tempDir = getServletContext().getRealPath("/WEB-INF/upload");  
        facotry.setRepository(new File(tempDir));//设置临时文件存放目录  
        // 2、创建核心解析类:ServletFileUpload  
        ServletFileUpload upload = new ServletFileUpload(facotry);  
        upload.setHeaderEncoding("UTF-8");// 解决上传的文件名乱码  
        upload.setFileSizeMax(1024 * 1024 * 1024);// 单个文件上传最大值是1M  
        upload.setSizeMax(2048 * 1024 * 1024);//文件上传的总大小限制  

        // 3、判断用户的表单提交方式是不是multipart/form-data  
        boolean bb = upload.isMultipartContent(request);  
        if (!bb) {  
            response.setCharacterEncoding("utf-8");
            response.getWriter().print("不是multipart/form-data");
            return;  
        }  
        // 4、是:解析request对象的正文内容List  
        List items = upload.parseRequest(request);  

      String dirString =path.substring(0,path.lastIndexOf("/"));
       String filenameString=path.substring(path.lastIndexOf("/")+1);
        String storePath = getServletContext().getRealPath(dirString);// 上传的文件的存放目录  
        for (FileItem item : items) {  
            if (item.isFormField()) {  
                // 5、判断是否是普通表单:打印看看  
                String fieldName = item.getFieldName();// 请求参数名  
                String fieldValue = item.getString("UTF-8");// 请求参数值  
                System.out.println(fieldName + "=" + fieldValue);  
            } else {  
                // 6、上传表单:得到输入流,处理上传:保存到服务器的某个目录中,保存时的文件名是啥?  
                String fileName = item.getName();// 得到上传文件的名称 C:\Documents  
                                                    // and  
                                                    // Settings\shc\桌面\a.txt  
                                                    // a.txt  
                //解决用户没有选择文件上传的情况  
                if(fileName==null||fileName.trim().equals("")){  
                    continue;  
                }  
                fileName = fileName  
                        .substring(fileName.lastIndexOf("\\") + 1);  
                String newFileName = fileName;  
                System.out.println("上传的文件名是:" + filenameString);  
                InputStream in = item.getInputStream();  
                String savePath = makeDir(storePath, filenameString);  
                OutputStream out = new FileOutputStream(savePath);  
                byte b[] = new byte[1024];  
                int len = 0;  
                while ((len = in.read(b)) != -1) {  
                    out.write(b, 0, len);  
                }  
                in.close();  
                out.close();  
                item.delete();//删除临时文件  
                
                response.getWriter().print(fileName);
            }  
        }  
    }catch(FileUploadBase.FileSizeLimitExceededException e){  
        response.getWriter().print("单个文件大小不能超出5M");
        request.setAttribute("message", "单个文件大小不能超出5M");  
        request.getRequestDispatcher("/message.jsp").forward(request,  
                response);  
    }catch(FileUploadBase.SizeLimitExceededException e){  
        response.getWriter().print("总文件大小不能超出7M");
}catch (Exception e) {  
        e.printStackTrace();  
        response.getWriter().print("上传失败");
    }  

服务端 String path= request.getParameter("path"); 为null。
Part part1= request.getPart("path"); 这个是有的 但是变成流了

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有