1. 程式人生 > >java從伺服器上傳本地圖片到圖片伺服器

java從伺服器上傳本地圖片到圖片伺服器

原文地址

http://blog.csdn.net/xingfeichen/article/details/54378790

1,本地上傳程式碼

  1. /** 
  2.  * 圖片上傳 
  3.  * </p> 
  4.  * @param avatarImgPath 
  5.  * @return 
  6.  */
  7. private String uploadImgToServer(String avatarImgPath) {  
  8.     MultipartEntityBuilder builders = MultipartEntityBuilder.create();  
  9.     FileBody imgage = new FileBody(
    new File(avatarImgPath));  
  10.     builders.addPart("img1", imgage);  
  11.     HttpEntity reqEntitys = builders.build();  
  12.     String results = HttpClientPostUtils  
  13.             .postMultiPart("http://192.168.0.221:8080/uploadweb/imgUpload/taskExecuteImg", reqEntitys);  
  14.     return results;  
  15. }  

  1. publicstatic String postMultiPart(String url,HttpEntity reqEntity){  
  2.         CloseableHttpClient httpclient = HttpClients.createDefault();  
  3.         try{  
  4.             HttpPost method = new HttpPost(url);  
  5.             // MultipartEntity reqEntity = new MultipartEntity();  
  6.             method.setEntity(reqEntity);  
  7.              CloseableHttpResponse response = httpclient.execute(method);  
  8.              try{              
  9.             //HttpResponse response=httpClient.execute(method); 
  10.             int statusCode = response.getStatusLine().getStatusCode();  
  11.             if(statusCode == HttpStatus.SC_OK){  
  12.                 String body=EntityUtils.toString(response.getEntity());   
  13.                 return body;    
  14.             }}finally{  
  15.                  response.close();  
  16.              }  
  17.         }catch(Exception e){  
  18.             e.printStackTrace();  
  19.         }finally{  
  20.             try {  
  21.                 httpclient.close();  
  22.             } catch (IOException e) {  
  23.                 // TODO Auto-generated catch block
  24.                 e.printStackTrace();  
  25.             }  
  26.         }  
  27.         returnnull;  
  28.     }  
2,服務端上圖片處理程式碼
  1. /** 
  2.      * 儲存圖片到本地 
  3.      * </p> 
  4.      * @param isDefaultSuffix 
  5.      *                  是否使用預設字尾名 
  6.      * @param path 
  7.      *                  圖片相對路徑 
  8.      * @param type 
  9.      *                  圖片型別 
  10.      * @param request 
  11.      * @param response 
  12.      * @return 
  13.      */
  14.     private String saveImgByType(boolean isDefaultSuffix, String path, String type, MultipartHttpServletRequest request,  
  15.             HttpServletResponse response) {  
  16. //      if (this.isUploadBlank(request)) {
  17. //          logger.error("upload" + type + " img is null------上傳檔案為空");
  18. //          return "";
  19. //      }
  20.         logger.info("upload" + type + " img start path: " + path);  
  21.         Iterator<String> itr = request.getFileNames();  
  22.         MultipartFile mpf = null;  
  23.         while (itr.hasNext()) {  
  24.             try {  
  25.                 mpf = request.getFile(itr.next());  
  26.                 if(mpf.isEmpty()){  
  27.                     logger.error("upload" + type + " img is null------上傳檔案為空");  
  28.                     returnnull;  
  29.                 }  
  30.                 //
  31.                 int imgSzie = mpf.getInputStream().available();  
  32.                 // 獲取檔名
  33.                 String fileName = mpf.getOriginalFilename();  
  34.                 if (StringUtils.isBlank(fileName)) {  
  35.                     logger.error("檔名為空");  
  36.                     returnnull;  
  37.                 }  
  38.                 // 檔案字尾
  39.                 String suffix = ".png";  
  40.                 if(!isDefaultSuffix){  
  41.                     suffix = fileName.substring(fileName.lastIndexOf("."));  
  42.                 }  
  43.                 if (mpf.getSize() / 1000 <= 30000 && mpf.getSize() == imgSzie) {  
  44.                     // 圖片相對路徑
  45.                     String imgPath = path;  
  46.                     if (StringUtils.isBlank(imgPath)) {  
  47.                         imgPath = "files" + File.separator + getImagePath(type) + suffix; // 獲得目錄下的相對路徑
  48.                     }  
  49.                     // 圖片絕對路徑
  50.                     String originalName = MyFileUtil.FILE_PATH + File.separator + imgPath;  
  51.                     // 儲存圖片
  52.                     MyFileUtil.saveInputStreamToFile(mpf.getInputStream(), originalName);  
  53.                     // 只針對任務和任務執行的圖片進行壓縮
  54.                     if (originalName.contains(File.separator + IMG_TYPE_TASK + File.separator)  
  55.                             || originalName.contains(File.separator + IMG_TYPE_TASKEXE + File.separator)) {  
  56.                         // 獲取縮圖路徑
  57.                         String smallImgPath = getSmallImgName(originalName);  
  58.                         if (StringUtils.isNotBlank(smallImgPath)) {  
  59.                             // 臨時儲存變數
  60.                             String tempPath = MyFileUtil.FILE_PATH + File.separator + "temp" + File.separator  
  61.                                     + System.currentTimeMillis() + ".png";  
  62.                             String parentPath = MyFileUtil.FILE_PATH + File.separator + "temp" + File.separator;  
  63.                             File parentFile = new File(parentPath);  
  64.                             if (!(parentFile.exists() && parentFile.isDirectory())) {  
  65.                                 parentFile.mkdir();  
  66.                             }  
  67.                             // 按比例縮放(放大縮小)false為縮小,true為放大
  68.                             ImageUtils.scale(originalName, tempPath, 4false);  
  69.                             ImageHelper.cutCenterImage(tempPath, smallImgPath, ImageUtils.SMALL_IMG_WIDTH,  
  70.                                     ImageUtils.SMALL_IMG_HEIGHT);  
  71.                             new File(tempPath).deleteOnExit();  
  72.                         }  
  73.                     }  
  74.                     logger.info(imgPath + " 圖片上傳成功");  
  75.                     return imgPath;  
  76.                 } else {  
  77.                     if (mpf.getSize() != imgSzie) {  
  78.                         logger.error("#######圖片上傳失敗,伺服器獲取到圖片大小(位元組): " + mpf.getSize() + ", 上傳圖片實際大小(位元組): " + imgSzie);  
  79.                     } else {  
  80.                         logger.error("單張照片不得超過30M");  
  81.                     }  
  82.                     returnnull;  
  83.                 }  
  84.             } catch (IOException e) {  
  85.                 logger.error(e.getMessage());  
  86.                 returnnull;  
  87.             }  
  88.         }  
  89.         logger.error("沒有上傳的圖片");  
  90.         returnnull;  
  91.     }  

  1. /** 
  2.  * 獲取縮圖路徑  
  3.  * <br> 
  4.  * @param originalName 
  5.  * @return 
  6.  */
  7. private String getSmallImgName(String originalName) {  
  8.     if (StringUtils.isBlank(originalName))  
  9.         returnnull;  
  10.     int