跨系统上传文件方法调用实现

	/****
	 * 上传图片到访客系统
	 * @param url
	 * @param file
	 * @param mac
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public  String PostImg(String url, MultipartFile[] file,String mac,String key) throws Exception {
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		try {
			httpclient = HttpClients.createDefault();
			HttpPost post = new HttpPost(url);		
			//CommonsMultipartFile cf= (CommonsMultipartFile)file[0]; 
	        //DiskFileItem fi = (DiskFileItem)cf.getFileItem(); 
	        //File f = fi.getStoreLocation();	 
			//String suffix = file[0].getOriginalFilename().substring(file[0].getOriginalFilename().lastIndexOf("."));     
		   // String fileName = UUID.randomUUID().toString()+ suffix; 
		  //  File f=new File(fileName);
			FileBody fileBody = new FileBody(multipartToFile(file[0]));
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
			StringBody mock_key = new StringBody(key); 
			StringBody macAddress = new StringBody(mac); 
			builder.addPart("file", fileBody);
			builder.addPart("mock_key", mock_key);
			builder.addPart("macAddress", macAddress);
			HttpEntity entity = builder.build();
			post.setEntity(entity);			
			response = httpclient.execute(post);
			if (200 == response.getStatusLine().getStatusCode()) {
				HttpEntity resultentity = response.getEntity();
				String entityString = EntityUtils.toString(resultentity, "utf-8");
				EntityUtils.consume(resultentity);
				return entityString;
			} else {
				return "";
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (response != null) {
				response.close();
			}
			if (httpclient != null) {
				httpclient.close();
			}
		}
	}
	
	/** 
     * MultipartFile 转换成File 
     *  
     * @param multfile 原文件类型 
     * @return File 
     * @throws IOException 
     */  
    private File multipartToFile(MultipartFile multfile) throws IOException {  
 
			// 生成uuid作为文件名称
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			// 获得文件类型(可以判断如果不是图片,禁止上传)
			String contentType = multfile.getContentType();
			// 获得文件后缀名称
			String imageName = contentType.substring(contentType.indexOf("/") + 1);
			String	path = uuid + "." + imageName;
			File tmpFile=new File(baseUrl + path);
			multfile.transferTo(tmpFile);      
        return tmpFile;  
    }  

 

posted on 2018-01-26 15:20  让代码飞  阅读(152)  评论(0)    收藏  举报

导航

一款免费在线思维导图工具推荐:https://www.processon.com/i/593e9a29e4b0898669edaf7f?full_name=python