RestTemplate后台下载文件demo

@RequestMapping(path="/test", method=RequestMethod.GET)
	public void productDat2(@RequestParam final Long id, HttpServletResponse response) {
		Xxx byId = xxxService.getById(id);
		if (byId == null){
			throw new BusinessException(-1,"数据异常!");
		}
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		HttpEntity<Resource> httpEntity = new HttpEntity<Resource>(headers);
		ResponseEntity<byte[]> bytes = restTemplate.exchange(configProperties.getFileServerUrl()+"/file/download/"+byId.getFileId(),  HttpMethod.GET,httpEntity, byte[].class);
		File f = new File("d://aa.dat");
		if (!f.exists()){
			try {
				f.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(f);
			out.write(bytes.getBody(),0,bytes.getBody().length);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if (out!=null){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

  

posted on 2018-12-04 17:15  开心就好呀·  阅读(3747)  评论(0编辑  收藏  举报

导航