1. 程式人生 > >RestTemplate後臺下載檔案demo

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();
				}
			}
		}

	}