使用 RestTemplate 上传文件代码: https://blog.csdn.net/weixin_44953227/article/details/124636293
下载代码
package com.pro.web;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.pro.common.exception.BusinessException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.UUID;
@RestController
@RequestMapping("/download")
public class DownloadController {
protected Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private RestTemplate restTemplate;
/**
* 文件下载
*
* @param documentPath
* @param response
* @throws BusinessException
*/
@GetMapping("/file")
public void downloadFile(String documentPath, HttpServletResponse response) throws BusinessException {
if (StringUtils.isBlank(documentPath)) {
throw BusinessException.withErrorMsg("文档地址为空");
}
HttpHeaders httpHeaders = new HttpHeaders();
HttpEntity<String> httpEntity = new HttpEntity<>(httpHeaders);
String url = String.format("https://img-home.csdnimg.cn/images/20201124032511.png");
logger.info(">>> 下载文件url: {}", url);
URI uri = null;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
logger.error("uri 异常", e);
throw BusinessException.withErrorMsg(e);
}
ResponseEntity<byte[]> responseEntity = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, byte[].class);
logger.warn(">>> responseEntity: {}", responseEntity);
if (responseEntity.getStatusCodeValue() != HttpStatus.OK.value()) {
logger.error(">>> 状态码异常: {}", responseEntity.getStatusCodeValue());
throw BusinessException.withErrorMsg(String.format("状态码异常 %s", responseEntity.getStatusCodeValue()));
}
// 把 body 数据写入输出流
byte[] data = responseEntity.getBody();
if (data == null) {
throw BusinessException.withErrorMsg("文件为空");
}
ServletOutputStream outputStream = null;
try {
String uid = UUID.randomUUID().toString().replace("-", "");
String fileName = String.format("%s_%s.png", uid, documentPath);
// 设置这两个参数后浏览器会自动下载, 这两个参数可以不设置, 不设置在会在浏览器中显示文件内容
response.setContentType("application/x-msdownload");
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
outputStream = response.getOutputStream();
// 输出
outputStream.write(data);
outputStream.flush();
} catch (IOException e) {
logger.error("IOException", e);
} finally {
// 关闭流
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
logger.error("close IOException", e);
}
}
}
}
}