Idea使用HttpClicnt模拟上传文件:

模拟前提是已经搭建好SpringMVC环境配置:
1、建一个maven项目,属于jar包然后建一个UploadFileDemo类,里面写:

 	@Test
    public void uploadFile() throws IOException {
        //1、得到CloseableHttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2、得到HttpPost对象
        HttpPost httppost=new HttpPost("http://localhost:8080/getFile");
        //3、得到准备上传文件的完整路径
        File file = new File("D:\\files\\IO练习文件\\photo\\bground2.jpg");
        FileBody filebody = new FileBody(file);
        //4、把文件封装到HttpEntity对象(1、设定封包模式,浏览器兼容模式2、添加上传的文件3、编译生成)
        HttpEntity entity= MultipartEntityBuilder.create()
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                .addPart("testFile", filebody)
                .build();
        //5、把封装好的HttpEntity对象封装到HttpPOST请求
        httppost.setEntity(entity);
        //6、执行post请求,获取返回对象HttpResponse
        HttpResponse httpresponse=httpClient.execute(httppost);
        //7、打印返回状态码
        System.out.println("返回状态码:"+httpresponse.getStatusLine());
        //8、得到内容对象Entity,服务器端是跳转到一个页面的,所以这里打印html标签
        HttpEntity entityreturn = httpresponse.getEntity();
        //9、利用EntityUtils工具类来处理返回的Entity对象,获得字符串
        System.out.println("返回值:"+ EntityUtils.toString(entityreturn));
        //10、关闭连接
        httpClient.close();

    }

2、controller类那里写:

//客户端上传文件
    @RequestMapping("/getFile")
    public String getFile(@RequestParam("testFile")MultipartFile testFile, HttpServletRequest request){
        try {
            String fileName = testFile.getOriginalFilename();
            //这里路径一定要是你项目存放图片的位置,在webpapp文件夹下的
            String serverPath="C:\\Users\\Administrator\\IdeaProjects\\httpclient\\src\\main\\webapp\\images";
            //下面是tomcat容器的路径,不要保存在这里,每次重启tomcat文件就会没的,处理客户端下载请求可以这样写
            //String serverPath = request.getSession().getServletContext().getRealPath("images");
            File judgeFile=new File(serverPath);
            if(!judgeFile.exists()){
                judgeFile.mkdir();
            }
            File lastFile=new File(serverPath,fileName);
            testFile.transferTo(lastFile);
            System.out.println("文件上传成功\n"+"文件位置:"+lastFile+"文件名字:"+lastFile.getName());
            } catch (IOException e) {
                e.printStackTrace();
            }
        return  "uploadResult";
    }

3、先启动controller那边的服务器,再run uploadFile()方法即可,会返回成功,controller那边也会有打印。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值