Compare commits

...

7 Commits

7 changed files with 106 additions and 3 deletions

View File

@ -0,0 +1,65 @@
package org.cmh.backend.NewsManagement.controller;
import org.cmh.backend.NewsManagement.dto.UploadFileResponse;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@RestController
@CrossOrigin // 如果前端和后端不在同一个域名或端口下需要启用跨域
public class FileController {
private static final String UPLOAD_DIR = "uploads/";
@PostMapping("/news/uploadPic")
public ResponseEntity<UploadFileResponse> uploadFile(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return new ResponseEntity<>(new UploadFileResponse("文件不能为空", null), HttpStatus.BAD_REQUEST);
}
try {
// 确保上传目录存在
Path uploadDirPath = Paths.get(UPLOAD_DIR);
if (!Files.exists(uploadDirPath)) {
Files.createDirectories(uploadDirPath);
}
// 生成文件路径
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOAD_DIR + file.getOriginalFilename());
Files.write(path, bytes);
// 返回成功信息
return new ResponseEntity<>(new UploadFileResponse("文件上传成功", "/api/news/files/" + file.getOriginalFilename()), HttpStatus.OK);
} catch (IOException e) {
return new ResponseEntity<>(new UploadFileResponse("文件上传失败", null), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping("/news/files/{filename}")
public ResponseEntity<Resource> getFile(@PathVariable String filename) {
try {
Path filePath = Paths.get(UPLOAD_DIR).resolve(filename).normalize();
Resource resource = new UrlResource(filePath.toUri());
if (resource.exists() && resource.isReadable()) {
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

View File

@ -24,6 +24,15 @@ public class NewsController {
return new ResponseEntity<>(newsService.getNewsByPage(pageNo, pageSize), HttpStatus.OK);
}
@GetMapping("/{id}")
public ResponseEntity<News> getNewsPage(@PathVariable Long id) {
try {
return new ResponseEntity<>(newsService.getNewsById(id), HttpStatus.OK);
} catch (EntityNotFoundException e) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@PostMapping
@JwtVerify
public ResponseEntity<MessageResponse> createNews(@RequestBody NewsRequest request) {
@ -34,7 +43,7 @@ public class NewsController {
} catch (Exception e) {
return new ResponseEntity<>(new MessageResponse("创建失败:" + e.getMessage()), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(new MessageResponse("创建成功"), HttpStatus.OK);
return new ResponseEntity<>(new MessageResponse("创建成功"), HttpStatus.CREATED);
}
@PutMapping("/{id}")

View File

@ -12,4 +12,5 @@ public class NewsRequest extends JwtRequest {
private String content;
private String imagePath;
private String author;
private String tenant;
}

View File

@ -0,0 +1,16 @@
package org.cmh.backend.NewsManagement.dto;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class UploadFileResponse extends MessageResponse {
private String url;
public UploadFileResponse(String message, String url) {
super(message);
this.url = url;
}
}

View File

@ -31,4 +31,6 @@ public class News {
@CreationTimestamp
private LocalDateTime createdAt;
private String tenant;
}

View File

@ -50,8 +50,15 @@ public class NewsService {
public void deleteNews(Long id) {
if (!newsRepository.existsById(id)) {
throw new EntityNotFoundException("News with id " + id + " not found.");
throw new EntityNotFoundException();
}
newsRepository.deleteById(id);
}
public News getNewsById(Long id) {
if (!newsRepository.existsById(id)) {
throw new EntityNotFoundException();
}
return newsRepository.findById(id).orElse(null);
}
}

View File

@ -22,5 +22,8 @@ server.servlet.encoding.force=true
server.servlet.encoding.charset=utf-8
# verificationCode
verification.code.images.path=src/main/resources/static/verificationCodeImages
# set the max size of a single file
spring.servlet.multipart.max-file-size=50MB
# set the max size of the total request
spring.servlet.multipart.max-request-size=50MB