Skip to content

Commit

Permalink
add token for preview static sources
Browse files Browse the repository at this point in the history
  • Loading branch information
Jarrettluo committed Jul 22, 2024
1 parent 3df3a01 commit b122a4b
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 11 deletions.
15 changes: 15 additions & 0 deletions src/main/java/com/jiaruiblog/config/CommonExceptionHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.http.HttpServletResponse;
Expand Down Expand Up @@ -108,6 +110,19 @@ public void dealAuthenticationException(HttpServletResponse response) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
}

/**
* @Author luojiarui
* @Description 管理员设置的禁止操作的错误
* @Date 21:18 2022/12/9
* @Param [e]
**/
@ExceptionHandler(MissingServletRequestParameterException.class)
public BaseApiResult dealAuthenticationException(MissingServletRequestParameterException e, HandlerMethod handlerMethod) {
String errorMessage = String.format("MissingServletRequestParameterException(遗漏Servlet请求参数异常):%s",
e.getMessage());
return BaseApiResult.error(MessageConstant.PARAMS_ERROR_CODE, errorMessage);
}

}


47 changes: 36 additions & 11 deletions src/main/java/com/jiaruiblog/controller/FileController.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.auth0.jwt.interfaces.Claim;
import com.google.common.collect.Lists;
import com.jiaruiblog.common.MessageConstant;
import com.jiaruiblog.entity.FileDocument;
Expand All @@ -16,6 +17,7 @@
import com.jiaruiblog.service.TaskExecuteService;
import com.jiaruiblog.util.BaseApiResult;
import com.jiaruiblog.util.FileContentTypeUtils;
import com.jiaruiblog.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
Expand Down Expand Up @@ -79,14 +81,24 @@ public List<FileDocument> list(@ModelAttribute BasePageDTO basePageDTO) {
*/
@ApiOperation(value = "查询文档预览结果")
@GetMapping("/view/{id}")
public ResponseEntity<Object> serveFileOnline(@PathVariable String id) throws UnsupportedEncodingException {
public ResponseEntity<Object> serveFileOnline(@PathVariable String id,
@RequestParam("token") String token,
HttpServletResponse response)
throws UnsupportedEncodingException {
Map<String, Claim> userData = JwtUtil.verifyToken(token);
if (CollectionUtils.isEmpty(userData)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return null;
}
Optional<FileDocument> file = fileService.getById(id);
if (file.isPresent()) {
return ResponseEntity.ok()
// 这里需要进行中文编码
.header(HttpHeaders.CONTENT_DISPOSITION, "fileName=" + URLEncoder.encode(file.get().getName(), "utf-8"))
.header(HttpHeaders.CONTENT_DISPOSITION,
"fileName=" + URLEncoder.encode(file.get().getName(), "utf-8"))
.header(HttpHeaders.CONTENT_TYPE, file.get().getContentType())
.header(HttpHeaders.CONTENT_LENGTH, file.get().getSize() + "").header("Connection", "close")
.header(HttpHeaders.CONTENT_LENGTH, file.get().getSize() + "")
.header("Connection", "close")
.header(HttpHeaders.CONTENT_LENGTH, file.get().getSize() + "")
.body(file.get().getContent());
} else {
Expand All @@ -98,7 +110,7 @@ public ResponseEntity<Object> serveFileOnline(@PathVariable String id) throws Un
* 在线显示文件
*
* @param id 文件id
* @return
* @return ResponseEntity<Object> 返回实体
*/
@GetMapping("/view2/{id}")
public ResponseEntity<Object> previewFileOnline(@PathVariable String id) throws UnsupportedEncodingException {
Expand All @@ -119,8 +131,8 @@ public ResponseEntity<Object> previewFileOnline(@PathVariable String id) throws
/**
* 下载附件
*
* @param id
* @return
* @param id 请求文件id
* @return ResponseEntity<Object>
* @throws UnsupportedEncodingException
*/
@GetMapping("/{id}")
Expand Down Expand Up @@ -288,7 +300,7 @@ public BaseApiResult uploadBatch(FileUploadDTO fileUploadDTO, HttpServletRequest
tags = tags.subList(0, 10);
}
// 当只上传一个文档的时候,跳过错误肯定是False
if (files.length <2) {
if (files.length < 2) {
skipError = Boolean.FALSE;
}
return fileService.uploadBatch(category, tags, description, skipError, files, userId, username);
Expand Down Expand Up @@ -325,11 +337,11 @@ public BaseApiResult uploadByUrl(@RequestBody UrlUploadDTO urlUploadDTO, HttpSer
}

/**
* @return java.lang.Boolean
* @Author luojiarui
* @Description 文件上传时的参数检查:长度要求;格式要求;敏感词要求
* @Date 16:14 2023/4/22
* @Param [tags, category, description, name]
* @return java.lang.Boolean
**/
private static Boolean checkParam(List<String> tags, String category, String description, String name) {

Expand Down Expand Up @@ -427,7 +439,14 @@ public ResponseModel deleteFileByGetMethod(@PathVariable String id) {
**/
@GetMapping(value = "/image/{thumbId}", produces = MediaType.IMAGE_PNG_VALUE)
@ResponseBody
public byte[] previewThumb(@PathVariable String thumbId) throws Exception {
public byte[] previewThumb(@PathVariable String thumbId,
@RequestParam("token") String token,
HttpServletResponse response) throws Exception {
Map<String, Claim> userData = JwtUtil.verifyToken(token);
if (CollectionUtils.isEmpty(userData)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return new byte[]{};
}
InputStream inputStream = fileService.getFileThumb(thumbId);
FileInputStream fileInputStream = (FileInputStream) (inputStream);
if (inputStream == null) {
Expand Down Expand Up @@ -471,7 +490,14 @@ public ResponseEntity<Object> previewThumb1(@PathVariable String id) {

@GetMapping(value = "/image2/{thumbId}", produces = MediaType.IMAGE_PNG_VALUE)
@ResponseBody
public byte[] previewThumb2(@PathVariable String thumbId, HttpServletResponse response) {
public byte[] previewThumb2(@PathVariable String thumbId,
@RequestParam("token") String token,
HttpServletResponse response) {
Map<String, Claim> userData = JwtUtil.verifyToken(token);
if (CollectionUtils.isEmpty(userData)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return new byte[]{};
}
// 设置响应头,缓存 1 小时
response.setHeader("Cache-Control", "max-age=3600, public");
return fileService.getFileBytes(thumbId);
Expand Down Expand Up @@ -583,7 +609,6 @@ public BaseApiResult temporaryFileDownloadLink() {
// }



return BaseApiResult.success();
}
}

0 comments on commit b122a4b

Please sign in to comment.