feat: add upload img logic
This commit is contained in:
@@ -3,7 +3,9 @@ package xin.merlin.myblog_server.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import xin.merlin.myblog_server.entity.Article;
|
||||
import xin.merlin.myblog_server.entity.Comment;
|
||||
import xin.merlin.myblog_server.entity.News;
|
||||
@@ -15,6 +17,14 @@ import xin.merlin.myblog_server.utils.JwtUtil;
|
||||
import xin.merlin.myblog_server.utils.RequestBack;
|
||||
import xin.merlin.myblog_server.utils.enums.ResultCode;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/admin")
|
||||
public class AdminController {
|
||||
@@ -32,6 +42,9 @@ public class AdminController {
|
||||
@Autowired
|
||||
private CommentServiceImpl commentService;
|
||||
|
||||
@Value("${upload.dir}")
|
||||
private String uploadDir;
|
||||
|
||||
//编辑,新增,删除新闻
|
||||
@PostMapping("/update/news")
|
||||
RequestBack editNews(@RequestBody News news, @RequestHeader("Authorization")String token) {
|
||||
@@ -100,4 +113,30 @@ public class AdminController {
|
||||
commentService.removeById(user.getId());
|
||||
return RequestBack.success(ResultCode.SUCCESS);
|
||||
}
|
||||
|
||||
//上传照片
|
||||
@PostMapping("/upload/img")
|
||||
RequestBack uploadImg(@RequestHeader("Authorization")String token, @RequestParam("image") MultipartFile file) throws IOException {
|
||||
if(!jwtUtil.getUAccount(token.substring(7)).equals("admin")) return RequestBack.fail(ResultCode.USER_NOT_FOUND);
|
||||
if (file == null || file.isEmpty()) {
|
||||
return RequestBack.fail(ResultCode.NOT_FOUND);
|
||||
}
|
||||
String original = file.getOriginalFilename();
|
||||
String ext = "";
|
||||
if (original != null && original.contains(".")) {
|
||||
ext = original.substring(original.lastIndexOf('.'));
|
||||
}
|
||||
|
||||
String filename = UUID.randomUUID().toString() + ext;
|
||||
|
||||
Path dirPath = Paths.get(uploadDir);
|
||||
Files.createDirectories(dirPath);
|
||||
|
||||
Path target = dirPath.resolve(filename);
|
||||
try (InputStream in = file.getInputStream()) {
|
||||
Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
|
||||
return RequestBack.success(ResultCode.SUCCESS, "https://blog.merlin.xin/app/uploads/"+filename);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user