spring boot 用RestTemplate post 在服务器间传送文件

@Controller
@RequestMapping(value = "/client")
public class FileServerAtClient {
 
	@RequestMapping(value = "/upload1", method = RequestMethod.POST)
	public @ResponseBody String upload1() {
		String url = "http://restAddr/lyy-test/service/upload1";
		String filePath = "E:/fileServer/client/upload/upload.png";
 
		RestTemplate rest = new RestTemplate();
		
		FileSystemResource resource = new FileSystemResource(new File(filePath));
		MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
		param.add("file", resource);
		param.add("fileName", "xiaolian.png");
	
		// method 1
		String string = rest.postForObject(url, param, String.class);
		// method 2
//		HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String,Object>>(param);
//		ResponseEntity<String> responseEntity = rest.exchange(url, HttpMethod.POST, httpEntity, String.class);
//		String string = responseEntity.getBody();
		
		System.out.println(string);
		
		return "success";
	}
 
	@RequestMapping(value = "/download1", method = RequestMethod.GET)
	public @ResponseBody String download1() {
		String url = "http://restAddr/project/service/download1/kaola";
		String filePath = "E:/fileServer/client/download/kaola.jpg";
		InputStream inputStream = null;
		OutputStream outputStream = null;
				
		RestTemplate restTemplate = new RestTemplate();
		try {
			//		Object result = restTemplate.getForObject(url, Object.class);
			HttpHeaders headers = new HttpHeaders();
			ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<byte[]>(headers), byte[].class);
			byte[] result = response.getBody();
			inputStream = new ByteArrayInputStream(result);
			
			outputStream = new FileOutputStream(new File(filePath));
			
			int len = 0;
			byte[] buf = new byte[1024];
			while ((len = inputStream.read(buf, 0, 1024)) != -1) {
				outputStream.write(buf, 0, len);
			}
			outputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
			return "error"; 
		} finally {
			try {
				if(inputStream != null) inputStream.close();
				if(outputStream != null) outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
				System.err.println("数据流关闭异常!");
			}
		}
		
		return "success";
	}
}
@Controller
@RequestMapping(value = "service")
public class FileServerAtService {
	
	@SuppressWarnings("resource")
	@RequestMapping(value = "/download1/{name}", method = RequestMethod.GET)
	public void download1(@PathVariable("name") String name, HttpServletRequest request, HttpServletResponse response) throws Exception{
		File file = new File("E:/fileServer/server/download/server.jpg");
		if(file.isFile()){
			try {
				InputStream fileInput = new FileInputStream(file);
				OutputStream out = response.getOutputStream();
				
				byte[] buffer = new byte[4096];
				int n = 0;
				while (-1 != (n = fileInput.read(buffer)))
					out.write(buffer, 0, n);
				
			} catch (Exception e) {
				e.printStackTrace();
				System.err.println("Exception exit");
				return ;
			}
		} else {
			System.err.println("not found");
			return ;
		}
		System.out.println("success end");
		return ;
	}
	
	@RequestMapping(value = "/upload1", method = RequestMethod.POST)
	public @ResponseBody String upload1(MultipartFile file, MultipartHttpServletRequest request){
//		Map<String,String[]> requestParams = request.getParameterMap();
//		MultiValueMap<String,MultipartFile> map = request.getMultiFileMap(); // map.get("file").get(0) ==file
		
		String path = "E:/fileServer/server/upload/"+file.getOriginalFilename();
		
		OutputStream out = null;
		try {
			out = new FileOutputStream(path);
			Assert.notNull(file, "No input byte array specified");
			out.write(file.getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			try {
				if(out !=null) out.close();
			}
			catch (IOException ex) {
			}
		}
		
		return "success";
	}
}

本地服务器上传到远程服务器

// 上传文件		
		FileSystemResource fileSystemResource = new FileSystemResource(fileNameWithPath);
		if (!fileSystemResource.exists()) {//文件不存在处理		
		}
		MediaType type = MediaType.parseMediaType("multipart/form-data");
		headers.setContentType(type);
		//headers.set("Cookie", cookies);//session用于验证身份
		MultiValueMap<String, Object> form = new LinkedMultiValueMap<String, Object>();
		form.add("file", fileSystemResource);
		//form.add("pass", finalpass);;//用于验证身份		
		HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
		responseEntity = restTemplate.postForEntity(urlTransfer, files, String.class);//发送
		//此处要添加错误处理	
		String result = responseEntity.getBody().toString();

从远程服务器下载到本地服务器

HttpHeaders headers = new HttpHeaders();
		HttpEntity<Resource> httpEntity = new HttpEntity<Resource>(headers);
		ResponseEntity<byte[]> response = restTemplate.exchange(getFilePath, HttpMethod.GET, httpEntity, byte[].class);

		if (response.getStatusCodeValue() != 200) {//异常处理
		
		}
		//写入本地
		try {
			File file = new File(path + File.separator + fileName);
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(response.getBody());
			fos.flush();
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值