Java spring-boot 프로젝트에서 spring-boot로 지정된 비정적 디렉토리에 파일 또는 사진을 업로드하고 다운로드하는 방법

질문

  • spring-boot 프로젝트는 정적 파일용 스토리지 디렉토리를 정의하지만 이 디렉토리는 일반적으로 프런트 엔드 정적 파일용 디렉토리로 사용됩니다. 이 정적 디렉토리를 파일을 업로드하는 디렉토리로 사용하면 다소 당황스러운 곳이 있을 것입니다. spring-boot를 jar 패키지로 패키징한 후 업로드된 사진 수가 증가함에 따라 jar 패키지도 커지고 in the jar 패키지에 있는 사진을 꺼내서 따로 보거나 편집하는 것은 매우 불편합니다.
  • 따라서 업로드된 파일의 디렉토리를 별도로 저장하기 위해 다른 파일 디렉토리를 정의해야 합니다.
  • 이것은 기본 가르침입니다. 우회하십시오. 본 후 더 나은 의견이 있으면 댓글 영역에서 지적하십시오. 다음은 시연용으로 직접 진행한 개인 프로젝트로, 불분명하거나 문제가 되는 부분이 있으면 댓글로 지적해 주시기 바랍니다.

업로드

여기서 범위 유형 AjaxResult는 Zoyi 프레임워크에서 가져온 HashMap에서 상속된 클래스입니다. 패키지 이름은 제가 변경한 적이 없어서 제가 직접 변경하겠습니다.

HttpStatus 클래스

 
 

자바

코드 복사

package com.example.xixieguan.utils; /** * 返回状态码 * * @author ruoyi */ public class HttpStatus { /** * 操作成功 */ public static final int SUCCESS = 200; /** * 对象创建成功 */ public static final int CREATED = 201; /** * 请求已经被接受 */ public static final int ACCEPTED = 202; /** * 操作已经执行成功,但是没有返回数据 */ public static final int NO_CONTENT = 204; /** * 资源已被移除 */ public static final int MOVED_PERM = 301; /** * 重定向 */ public static final int SEE_OTHER = 303; /** * 资源没有被修改 */ public static final int NOT_MODIFIED = 304; /** * 参数列表错误(缺少,格式不匹配) */ public static final int BAD_REQUEST = 400; /** * 未授权 */ public static final int UNAUTHORIZED = 401; /** * 访问受限,授权过期 */ public static final int FORBIDDEN = 403; /** * 资源,服务未找到 */ public static final int NOT_FOUND = 404; /** * 不允许的http方法 */ public static final int BAD_METHOD = 405; /** * 资源冲突,或者资源被锁 */ public static final int CONFLICT = 409; /** * 不支持的数据,媒体类型 */ public static final int UNSUPPORTED_TYPE = 415; /** * 系统内部错误 */ public static final int ERROR = 500; /** * 接口未实现 */ public static final int NOT_IMPLEMENTED = 501; /** * 系统警告消息 */ public static final int WARN = 601; }

AjaxResult 클래스

 
 

자바

코드 복사

package com.example.xixieguan.utils; import java.util.HashMap; public class AjaxResult extends HashMap<String, Object> { private static final long serialVersionUID = 1L; /** 状态码 */ public static final String CODE_TAG = "code"; /** 返回内容 */ public static final String MSG_TAG = "msg"; /** 数据对象 */ public static final String DATA_TAG = "data"; /** * 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。 */ public AjaxResult() { } /** * 初始化一个新创建的 AjaxResult 对象 * * @param code 状态码 * @param msg 返回内容 */ public AjaxResult(int code, String msg) { super.put(CODE_TAG, code); super.put(MSG_TAG, msg); } /** * 初始化一个新创建的 AjaxResult 对象 * * @param code 状态码 * @param msg 返回内容 * @param data 数据对象 */ public AjaxResult(int code, String msg, Object data) { super.put(CODE_TAG, code); super.put(MSG_TAG, msg); // super.put(DATA_TAG, data); if (data!=null) { super.put(DATA_TAG, data); } } /** * 返回成功消息 * * @return 成功消息 */ public static AjaxResult success() { return AjaxResult.success("操作成功"); } /** * 返回成功数据 * * @return 成功消息 */ public static AjaxResult success(Object data) { return AjaxResult.success("操作成功", data); } /** * 返回成功消息 * * @param msg 返回内容 * @return 成功消息 */ public static AjaxResult success(String msg) { return AjaxResult.success(msg, null); } /** * 返回成功消息 * * @param msg 返回内容 * @param data 数据对象 * @return 成功消息 */ public static AjaxResult success(String msg, Object data) { return new AjaxResult(HttpStatus.SUCCESS, msg, data); } /** * 返回警告消息 * * @param msg 返回内容 * @return 警告消息 */ public static AjaxResult warn(String msg) { return AjaxResult.warn(msg, null); } /** * 返回警告消息 * * @param msg 返回内容 * @param data 数据对象 * @return 警告消息 */ public static AjaxResult warn(String msg, Object data) { return new AjaxResult(HttpStatus.WARN, msg, data); } /** * 返回错误消息 * * @return 错误消息 */ public static AjaxResult error() { return AjaxResult.error("操作失败"); } /** * 返回错误消息 * * @param msg 返回内容 * @return 错误消息 */ public static AjaxResult error(String msg) { return AjaxResult.error(msg, null); } /** * 返回错误消息 * * @param msg 返回内容 * @param data 数据对象 * @return 错误消息 */ public static AjaxResult error(String msg, Object data) { return new AjaxResult(HttpStatus.ERROR, msg, data); } /** * 返回错误消息 * * @param code 状态码 * @param msg 返回内容 * @return 错误消息 */ public static AjaxResult error(int code, String msg) { return new AjaxResult(code, msg, null); } /** * 方便链式调用 * * @param key 键 * @param value 值 * @return 数据对象 */ @Override public AjaxResult put(String key, Object value) { super.put(key, value); return this; } }

컨트롤러 클래스

 
 

자바

코드 복사

package com.example.xixieguan.controller; import com.example.xixieguan.utils.AjaxResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ResourceLoader; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.UUID; @RestController @RequestMapping("/api") public class FileUploadController { private String separator = File.separator;//获取操作系统的文件分隔符 @Autowired private ResourceLoader resourceLoader; @PostMapping("/upload") public AjaxResult upload(@RequestParam("file") MultipartFile file) throws IOException { // 判断是否为空文件 AjaxResult ajaxResult = AjaxResult.error(); ajaxResult.put("msg","上传失败"); if (file.isEmpty()) { return ajaxResult; } // 获取文件名 String fileName = file.getOriginalFilename(); // 获取文件后缀 String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 重新生成文件名 fileName = UUID.randomUUID() + suffixName; // 设置文件存储路径 Path currentDir = Paths.get("images"); Path filePath = currentDir.toAbsolutePath(); if (!Files.exists(filePath)) { Files.createDirectory(filePath); } File dest = new File(filePath + separator + fileName); try { // 保存文件 file.transferTo(dest); ajaxResult = AjaxResult.success(); ajaxResult.put("msg","上传成功"); return ajaxResult; } catch (IOException e) { e.printStackTrace(); } return ajaxResult; } }

웹 구성 클래스 추가

  • 구성 패키지 아래에 추가하는 것이 좋습니다.
  • images 는 업로드된 파일을 저장하기 위해 제가 정의한 디렉토리 이름입니다. 필요에 따라 사용자 정의할 수 있습니다. 단, 업로드할 때 동일한 디렉토리 이름을 사용해야 하며, 그렇지 않으면 디렉토리를 찾을 수 없는 난처한 장면이 발생합니다.
 
 

자바

코드 복사

package com.example.xixieguan.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class StaticResourceConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/images/**") .addResourceLocations("file:./images/"); } }

위의 두 단계를 완료한 후 사진을 사용자 정의 디렉토리 위치에 이미 업로드할 수 있습니다. 그렇지 않은 경우 application.yml에 다른 구성을 추가하십시오.

application.yml

 
 

코드 복사

spring: web: resources: static-locations: file:./image/

위의 방법을 통해 Java spring-boot 프로젝트에서 파일이나 그림을 업로드하고 다운로드하는 기능적 요구 사항을 기본적으로 완료할 수 있으며 파일을 spring-boot의 정적 디렉토리에 둘 필요가 없다는 것이 핵심입니다. 유지보수의 번거로움이 줄어듭니다.

Guess you like

Origin blog.csdn.net/BASK2312/article/details/131811947