application.yml里面添加图片存放的位置

1
2
3
user:
file:
path: D:/home/data/schoolNews/

自己写上传和下载的方法



例如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.controller;


/**
* 上传文件映射表
*/
@RestController
@RequestMapping("file")
@SuppressWarnings({"unchecked","rawtypes"})
public class FileController{

@Value("${user.file.path}")
private String filePath;

@Autowired
private ConfigService configService;
/**
* 上传文件
*/
@RequestMapping("/upload")
public R upload(@RequestParam("file") MultipartFile file,String type) throws Exception {
if (file.isEmpty()) {
throw new EIException("上传文件不能为空");
}
String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
File upload = new File(filePath,"/upload/");
if(!upload.exists()) {
upload.mkdirs();
}
String fileName = new Date().getTime()+"."+fileExt;
File dest = new File(upload.getAbsolutePath()+"/"+fileName);
file.transferTo(dest);

if(StringUtils.isNotBlank(type) && type.equals("1")) {
ConfigEntity configEntity = configService.selectOne(new EntityWrapper<ConfigEntity>().eq("name", "faceFile"));
if(configEntity==null) {
configEntity = new ConfigEntity();
configEntity.setName("faceFile");
configEntity.setValue(fileName);
} else {
configEntity.setValue(fileName);
}
configService.insertOrUpdate(configEntity);
}
return R.ok().put("file", fileName);
}

/**
* 下载文件
*/
@IgnoreAuth
@RequestMapping("/download")
public ResponseEntity<byte[]> download(@RequestParam String fileName) {
try {
File upload = new File(filePath,"/upload/");
if(!upload.exists()) {
upload.mkdirs();
}
File file = new File(upload.getAbsolutePath()+"/"+fileName);
if(file.exists()){
/*if(!fileService.canRead(file, SessionManager.getSessionUser())){
getResponse().sendError(403);
}*/
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", fileName);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
}
} catch (IOException e) {
e.printStackTrace();
}
return new ResponseEntity<byte[]>(HttpStatus.INTERNAL_SERVER_ERROR);
}

}

添加映射让前端显示图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.config;


@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport{

@Value("${user.file.path}")
private String filePath;


@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("file:/" + filePath)
;
super.addResourceHandlers(registry);
}
}