Idea使用HttpClicnt模擬上傳檔案:
阿新 • • 發佈:2018-11-20
模擬前提是已經搭建好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那邊也會有列印。