controller层实现
/**
* 文件库模板下载
* @param
* @return
* @throws UnsupportedEncodingException
*/
@GetMapping("/downTemplate")
@ResponseBody
public ResponseEntity downTemplate(String projectItem) throws UnsupportedEncodingException {
//根据枚举结果获取对应类型是否有模板文件
if(!map.containsKey(projectItem)){
//projectItem不在枚举中
throw new RuntimeException("服务异常");
}
//文件名
String fileName = map.get(projectItem);
//设置HttpHeaders
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentDispositionFormData("attachment", URLEncoder.encode(fileName,"UTF-8"));
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//拼接url
String url = templateUrl + "/" + fileName;
//http调用
HttpResponse response = HttpRequest.get(url).setFollowRedirects(true).execute(false);
//获取文件字节流
byte[] bytes = response.bodyBytes();
return new ResponseEntity(bytes, httpHeaders, HttpStatus.OK);
}
其中templateUrl为:
map初始化代码:
private static Map<String,String> map = new HashMap<>();
@PostConstruct
void init(){
//初始化枚举中的模板数据到map中
if(map.size() <= 0){
for (ProjectTemplateEnum e : ProjectTemplateEnum.values()){
map.put(e.getCode(),e.getTemplate());
}
}
}
枚举类ProjectTemplateEnum为:
import lombok.Getter;
@Getter
public enum ProjectTemplateEnum {
/**
*十四五
*/
SSW("1","十四五项目下载模板.xls"),
BWYY("2","8511项目下载模板.xls"),
JBE("3","982项目下载模板.xls"),
YBA("4","已备案项目下载模板.xls"),
ZXZ("5","专项债项目下载模板.xls"),
SSZD("6","河南省重大项目下载模板.xls"),
SSZD2("7","漯河市重大项目下载模板.xls"),
SGYP("8","三个一批项目下载模板.xls"),
SGWB("9","三个五百项目下载模板.xlsx"),
GY("10","工业项目下载模板.xlsx"),
BZ("11","倍增工程项目下载模板.xlsx"),
SPMC("12","食品名城项目下载模板.xlsx"),
SPMC2("13","食品名城项目下载模板.xlsx");
private final String code;
private final String template;
ProjectTemplateEnum(String code,String template){
this.code = code;
this.template = template;
}
}
根据url在D盘中新建文件夹,并将枚举类的下载模板放在文件夹中