Skip to content

Commit a71243d

Browse files
committed
完成了本地存储功能,用户头像存储方式改为本地
1 parent 76242d4 commit a71243d

File tree

28 files changed

+703
-77
lines changed

28 files changed

+703
-77
lines changed

eladmin-common/src/main/java/me/zhengjie/redis/RedisConfig.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisC
6161
// 建议使用这种方式,小范围指定白名单
6262
ParserConfig.getGlobalInstance().addAccept("me.zhengjie.domain");
6363
ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.system.service.dto");
64+
ParserConfig.getGlobalInstance().addAccept("me.zhengjie.service.dto");
6465
ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.system.domain");
6566
ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.quartz.domain");
6667
ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.monitor.domain");

eladmin-common/src/main/java/me/zhengjie/utils/FileUtil.java

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,16 @@
44
import cn.hutool.core.util.IdUtil;
55
import cn.hutool.poi.excel.ExcelUtil;
66
import cn.hutool.poi.excel.ExcelWriter;
7+
import me.zhengjie.exception.BadRequestException;
78
import org.springframework.web.multipart.MultipartFile;
9+
import sun.misc.BASE64Encoder;
810

911
import javax.servlet.ServletOutputStream;
1012
import javax.servlet.http.HttpServletResponse;
1113
import java.io.*;
1214
import java.text.DecimalFormat;
15+
import java.text.SimpleDateFormat;
16+
import java.util.Date;
1317
import java.util.List;
1418
import java.util.Map;
1519

@@ -107,7 +111,7 @@ public static String getFileNameNoEx(String filename) {
107111
* @param size
108112
* @return
109113
*/
110-
public static String getSize(int size){
114+
public static String getSize(long size){
111115
String resultSize = "";
112116
if (size / GB >= 1) {
113117
//如果当前Byte的值大于等于1GB
@@ -147,6 +151,47 @@ public static File inputStreamToFile(InputStream ins, String name) throws Except
147151
return file;
148152
}
149153

154+
/**
155+
* 将文件名解析成文件的上传路径
156+
*
157+
* @param file
158+
* @param filePath
159+
* @return 上传到服务器的文件名
160+
*/
161+
public static File upload(MultipartFile file, String filePath) {
162+
Date date = new Date();
163+
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmssS");
164+
String name = getFileNameNoEx(file.getOriginalFilename());
165+
String suffix = getExtensionName(file.getOriginalFilename());
166+
String nowStr = "-" + format.format(date);
167+
try {
168+
String fileName = name + nowStr + "." + suffix;
169+
String path = filePath + fileName;
170+
File dest = new File(path);
171+
// 检测是否存在目录
172+
if (!dest.getParentFile().exists()) {
173+
dest.getParentFile().mkdirs();// 新建文件夹
174+
}
175+
String d = dest.getPath();
176+
file.transferTo(dest);// 文件写入
177+
return dest;
178+
} catch (Exception e) {
179+
e.printStackTrace();
180+
}
181+
return null;
182+
}
183+
184+
public static String fileToBase64(File file) throws Exception {
185+
FileInputStream inputFile = new FileInputStream(file);
186+
String base64 =null;
187+
byte[] buffer = new byte[(int)file.length()];
188+
inputFile.read(buffer);
189+
inputFile.close();
190+
base64=new BASE64Encoder().encode(buffer);
191+
String encoded = base64.replaceAll("[\\s*\t\n\r]", "");
192+
return encoded;
193+
}
194+
150195
/**
151196
* 导出excel
152197
* @param list
@@ -174,4 +219,26 @@ public static void downloadExcel(List<Map<String, Object>> list, HttpServletResp
174219
//此处记得关闭输出Servlet流
175220
IoUtil.close(out);
176221
}
222+
223+
public static String getFileType(String type) {
224+
String documents = "txt doc pdf ppt pps xlsx xls";
225+
String music = "mp3 wav wma mpa ram ra aac aif m4a";
226+
String video = "avi mpg mpe mpeg asf wmv mov qt rm mp4 flv m4v webm ogv ogg";
227+
String image = "bmp dib pcp dif wmf gif jpg tif eps psd cdr iff tga pcd mpt png jpeg";
228+
if(image.indexOf(type) != -1){
229+
return "图片";
230+
} else if(documents.indexOf(type) != -1){
231+
return "文档";
232+
} else if(music.indexOf(type) != -1){
233+
return "音乐";
234+
} else if(video.indexOf(type) != -1){
235+
return "视频";
236+
} else return "其他";
237+
}
238+
239+
public static void checkSize(long maxSize, long size) {
240+
if(size > (maxSize * 1024 * 1024)){
241+
throw new BadRequestException("文件超出规定大小");
242+
}
243+
}
177244
}

eladmin-system/src/main/java/me/zhengjie/config/ConfigurerAdapter.java

Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import com.fasterxml.jackson.databind.ObjectMapper;
44
import com.fasterxml.jackson.databind.module.SimpleModule;
55
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
6+
import org.springframework.beans.factory.annotation.Value;
67
import org.springframework.context.annotation.Configuration;
78
import org.springframework.http.converter.HttpMessageConverter;
89
import org.springframework.http.converter.StringHttpMessageConverter;
@@ -25,6 +26,12 @@
2526
@EnableWebMvc
2627
public class ConfigurerAdapter implements WebMvcConfigurer {
2728

29+
@Value("${file.path}")
30+
private String path;
31+
32+
@Value("${file.avatar}")
33+
private String avatar;
34+
2835
@Override
2936
public void addCorsMappings(CorsRegistry registry) {
3037
registry.addMapping("/**")
@@ -35,27 +42,12 @@ public void addCorsMappings(CorsRegistry registry) {
3542

3643
}
3744

38-
// 可解决Long 类型在 前端精度丢失的问题, 如不想全局 直接添加注解 @JsonSerialize(using= ToStringSerializer.class) 到相应的字段
39-
40-
// @Override
41-
// public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
42-
//
43-
// MappingJackson2HttpMessageConverter jackson2HttpMessageConverter =
44-
// new MappingJackson2HttpMessageConverter();
45-
//
46-
// ObjectMapper objectMapper = new ObjectMapper();
47-
// SimpleModule simpleModule = new SimpleModule();
48-
// simpleModule.addSerializer(BigInteger.class, ToStringSerializer.instance);
49-
// simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
50-
// simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
51-
// objectMapper.registerModule(simpleModule);
52-
// jackson2HttpMessageConverter.setObjectMapper(objectMapper);
53-
// converters.add(jackson2HttpMessageConverter);
54-
// converters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
55-
// }
56-
5745
@Override
5846
public void addResourceHandlers(ResourceHandlerRegistry registry) {
47+
String avatarUtl = "file:" + avatar.replace("\\","/");
48+
String pathUtl = "file:" + path.replace("\\","/");
49+
registry.addResourceHandler("/avatar/**").addResourceLocations(avatarUtl).setCachePeriod(0);
50+
registry.addResourceHandler("/file/**").addResourceLocations(pathUtl).setCachePeriod(0);
5951
registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/").setCachePeriod(0);
6052
}
6153
}

eladmin-system/src/main/java/me/zhengjie/modules/security/config/SecurityConfig.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,11 @@ protected void configure(HttpSecurity httpSecurity) throws Exception {
106106

107107
// 接口限流测试
108108
.antMatchers("/test/**").anonymous()
109+
// 文件
110+
.antMatchers("/avatar/**").anonymous()
111+
.antMatchers("/file/**").anonymous()
112+
113+
// 放行OPTIONS请求
109114
.antMatchers(HttpMethod.OPTIONS, "/**").anonymous()
110115

111116
.antMatchers("/druid/**").anonymous()

eladmin-system/src/main/java/me/zhengjie/modules/system/domain/User.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,9 @@ public class User implements Serializable {
3131
@Column(unique = true)
3232
private String username;
3333

34-
private String avatar;
34+
@OneToOne
35+
@JoinColumn(name = "avatar_id")
36+
private UserAvatar userAvatar;
3537

3638
@NotBlank
3739
@Pattern(regexp = "([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}",message = "格式错误")
@@ -69,7 +71,6 @@ public String toString() {
6971
return "User{" +
7072
"id=" + id +
7173
", username='" + username + '\'' +
72-
", avatar='" + avatar + '\'' +
7374
", email='" + email + '\'' +
7475
", enabled=" + enabled +
7576
", password='" + password + '\'' +
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package me.zhengjie.modules.system.domain;
2+
3+
import cn.hutool.core.util.ObjectUtil;
4+
import lombok.Data;
5+
import lombok.NoArgsConstructor;
6+
7+
import javax.persistence.*;
8+
import java.sql.Timestamp;
9+
10+
/**
11+
* @author Zheng Jie
12+
* @date 2019年9月7日 16:16:59
13+
*/
14+
@Entity
15+
@Table(name = "user_avatar")
16+
@Data
17+
@NoArgsConstructor
18+
public class UserAvatar {
19+
20+
@Id
21+
@GeneratedValue(strategy = GenerationType.IDENTITY)
22+
private Long id;
23+
24+
private String realName;
25+
26+
private String path;
27+
28+
private String size;
29+
30+
public UserAvatar(UserAvatar userAvatar,String realName, String path, String size) {
31+
this.id = ObjectUtil.isNotEmpty(userAvatar) ? userAvatar.getId() : null;
32+
this.realName = realName;
33+
this.path = path;
34+
this.size = size;
35+
}
36+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package me.zhengjie.modules.system.repository;
2+
3+
import me.zhengjie.modules.system.domain.UserAvatar;
4+
import org.springframework.data.jpa.repository.JpaRepository;
5+
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
6+
7+
import java.util.Date;
8+
9+
/**
10+
* @author Zheng Jie
11+
* @date 2018-11-22
12+
*/
13+
public interface UserAvatarRepository extends JpaRepository<UserAvatar, Long>, JpaSpecificationExecutor {
14+
15+
}

eladmin-system/src/main/java/me/zhengjie/modules/system/rest/UserController.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,8 +155,7 @@ public ResponseEntity updatePass(@RequestBody UserPassVo user){
155155
*/
156156
@PostMapping(value = "/users/updateAvatar")
157157
public ResponseEntity updateAvatar(@RequestParam MultipartFile file){
158-
Picture picture = pictureService.upload(file, SecurityUtils.getUsername());
159-
userService.updateAvatar(SecurityUtils.getUsername(),picture.getUrl());
158+
userService.updateAvatar(file);
160159
return new ResponseEntity(HttpStatus.OK);
161160
}
162161

eladmin-system/src/main/java/me/zhengjie/modules/system/service/UserService.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import org.springframework.cache.annotation.CacheEvict;
99
import org.springframework.cache.annotation.Cacheable;
1010
import org.springframework.data.domain.Pageable;
11+
import org.springframework.web.multipart.MultipartFile;
1112

1213
import javax.servlet.http.HttpServletResponse;
1314
import java.util.List;
@@ -67,11 +68,10 @@ public interface UserService {
6768

6869
/**
6970
* 修改头像
70-
* @param username
71-
* @param url
71+
* @param file
7272
*/
7373
@CacheEvict(allEntries = true)
74-
void updateAvatar(String username, String url);
74+
void updateAvatar(MultipartFile file);
7575

7676
/**
7777
* 修改邮箱

eladmin-system/src/main/java/me/zhengjie/modules/system/service/impl/MenuServiceImpl.java

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -197,15 +197,13 @@ public List<MenuVo> buildMenus(List<MenuDTO> menuDTOS) {
197197
if (menuDTO!=null){
198198
List<MenuDTO> menuDTOList = menuDTO.getChildren();
199199
MenuVo menuVo = new MenuVo();
200-
menuVo.setName(ObjectUtil.isNotEmpty(menuDTO.getComponentName()) ? menuDTO.getComponentName() : RandomUtil.randomString(5));
201-
menuVo.setPath(menuDTO.getPath());
200+
menuVo.setName(ObjectUtil.isNotEmpty(menuDTO.getComponentName()) ? menuDTO.getComponentName() : menuDTO.getName());
201+
// 一级目录需要加斜杠,不然会报警告
202+
menuVo.setPath(menuDTO.getPid() == 0 ? "/" + menuDTO.getPath() :menuDTO.getPath());
202203
menuVo.setHidden(menuDTO.getHidden());
203-
204204
// 如果不是外链
205205
if(!menuDTO.getIFrame()){
206206
if(menuDTO.getPid() == 0){
207-
//一级目录需要加斜杠,不然访问 会跳转404页面
208-
menuVo.setPath("/" + menuDTO.getPath());
209207
menuVo.setComponent(StrUtil.isEmpty(menuDTO.getComponent())?"Layout":menuDTO.getComponent());
210208
}else if(!StrUtil.isEmpty(menuDTO.getComponent())){
211209
menuVo.setComponent(menuDTO.getComponent());

0 commit comments

Comments
 (0)