Springboot使用RestTemplate上传和下载文件

上传文件代码

@Override
	public String uploadEnclosure(MultipartFile file) {
		RestTemplate template = new RestTemplate();
		MultiValueMap map = new LinkedMultiValueMap<>();
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("multipart/form-data");
        headers.setContentType(type);
        List fileList = new ArrayList<>();
        if (!file.isEmpty()){
            ByteArrayResource byteArrayResource;
			try {
				byteArrayResource = new ByteArrayResource(file.getBytes()){
				    @Override
				    public String getFilename() throws IllegalStateException {
				        return file.getOriginalFilename();
				    }
				};
			} catch (IOException e) {
				log.error("文件转换为字节流失败"+e.getMessage());
				return "文件转换为字节流失败";
			}
            fileList.add(byteArrayResource);
        }
        map.put("file", fileList);
        HttpEntity> request =
                new HttpEntity>(map, headers);
        String url = "http://"+gatewayIP.trim()+":"+gatewayPort.trim()+"/fileSystem/upload";	       
        ResponseEntity responseEntity;
        try {
			responseEntity = template.postForEntity(url, request, String.class);
			String body = responseEntity.getBody();
			JSONObject responseBody = JSON.parseObject(body);
			JSONObject data = responseBody.getJSONObject("data");
			String enclosure = data.getString("fileId")+"_"+file.getOriginalFilename();
			return enclosure;
		} catch (Exception e) {
			log.error("附件上传失败"+e.getMessage());
			throw new RuntimeException("附件上传失败");
		}
	}

下载文件代码

public void downloadEnclosure(Map params, HttpServletResponse response) {
		String fileId = (String) params.get("fileId");
		String fileName = (String) params.get("fileName");
		String url = "http://"+gatewayIP.trim()+":"+gatewayPort.trim()+"/fileSystem/download?fileId="+fileId;	
		RestTemplate restTemplate = new RestTemplate();
        ResponseEntity rsp = restTemplate.getForEntity(url,byte[].class);
        BufferedInputStream bis = null;
        OutputStream os = null;
        InputStream is = null;
        if (rsp!=null) {
            byte[] body = rsp.getBody();
            if (body!=null) {
                try {
                    log.info("文件大小==>:{}", body.length);
                    response.setContentType("application/octet-stream");
                    response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
                    is = new ByteArrayInputStream(body);
                    bis = new BufferedInputStream(is);
                    os = response.getOutputStream();
                    byte[] buffer = new byte[2048];
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    log.error("文件下载失败"+e.getMessage());
                    return;
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (os != null){
                        try {
                            os.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (is != null){
                        try {
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
		
	}

你可能感兴趣的:(Spring,SpringBoot,Java,java,restful)