模拟前提是已经搭建好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那边也会有打印。