|
@@ -27,24 +27,36 @@ public class UploadController {
|
|
|
if (file.isEmpty()) {
|
|
|
return ReturnMsg.fail("图片上传失败");
|
|
|
}
|
|
|
+
|
|
|
//可以自己加一点校验 例如上传的是不是图片或者上传的文件是不是png格式等等 这里省略
|
|
|
//获取原来的文件名和后缀
|
|
|
String originalFilename = file.getOriginalFilename();
|
|
|
// String ext = "." + FilenameUtils.getExtension(orgFileName); --需要导依赖
|
|
|
String ext = "."+ originalFilename.split("\\.")[1];
|
|
|
- //生成一个新的文件名(以防有重复的名字存在导致被覆盖)
|
|
|
- String uuid = UUID.randomUUID().toString().replace("-", "");
|
|
|
- String newName = uuid + ext;
|
|
|
- //拼接图片上传的路径 url+图片名
|
|
|
- ApplicationHome applicationHome = new ApplicationHome(this.getClass());
|
|
|
- String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\src\\main\\resources\\static\\images\\";
|
|
|
- String path = pre + newName;
|
|
|
- try {
|
|
|
- file.transferTo(new File(path));
|
|
|
- } catch (IOException e) {
|
|
|
- e.printStackTrace();
|
|
|
+ String type = originalFilename.indexOf(".") != -1 ? originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length()) : null;
|
|
|
+ if (type != null) {// 判断文件类型是否为空
|
|
|
+ if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {
|
|
|
+ //生成一个新的文件名(以防有重复的名字存在导致被覆盖)
|
|
|
+ String uuid = UUID.randomUUID().toString().replace("-", "");
|
|
|
+ String newName = uuid + ext;
|
|
|
+ //拼接图片上传的路径 url+图片名
|
|
|
+ ApplicationHome applicationHome = new ApplicationHome(this.getClass());
|
|
|
+ String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\src\\main\\resources\\static\\images\\";
|
|
|
+ String path = pre + newName;
|
|
|
+ try {
|
|
|
+ file.transferTo(new File(path));
|
|
|
+ } catch (IOException e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ }
|
|
|
+ return ReturnMsg.ok("/images/"+newName);
|
|
|
+ }else{
|
|
|
+ return ReturnMsg.fail("文件类型符合要求");
|
|
|
+ }
|
|
|
+
|
|
|
+ }else{
|
|
|
+ return ReturnMsg.fail("文件类型为空");
|
|
|
}
|
|
|
- return ReturnMsg.ok(path);
|
|
|
+
|
|
|
}
|
|
|
|
|
|
|