Java spring-boot项目中如何上传下载文件或图片到spring-boot规定的非静态目录

问题

  • spring-boot的项目,虽然它自己定义了一个静态文件的存储目录,但是这个目录一般是作为前端静态文件的目录来作为使用的。如果使用这个静态目录来作为我们上传文件的目录会有一个比较尴尬的地方:将spring-boot打包成为jar包后,随着上传图片的增多,这个jar包也会跟着变大,而且,在jar包中的图片要单独取出来查看或者编辑都极不方便。
  • 因此我们需要另外定义一个文件目录来单独存储我们上传文件的目录。
  • 这里是基础教学,大神请绕路,如果看到后有什么比较好的意见也欢迎评论区指出。以下以自己的一个个人项目来作为演示,有不清楚或有什么问题的地方,也请评论区指出。

上传

此处的范围类型 AjaxResult 是一个继承 HashMap 类,从若依框架上拿过来的。至于包名,我也没改,自己改一下吧

HttpStatus 类

 
 

java

复制代码

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类

 
 

java

复制代码

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; } }

controller类

 
 

java

复制代码

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; } }

添加web配置类

  • 建议添加在config包下
  • images是我自己定义用来存储上传文件的目录名,你可以根据自己的需求来定制。但是需要注意的是在上传的时候也需要是同样的目录名,不然会出现找不到目录的尴尬场面。
 
 

java

复制代码

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

 
 

yaml

复制代码

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

通过上述方式,已经基本可以完成 Java spring-boot项目上传下载文件或图片的功能需求,关键在于不用将文件放置到spring-boot的静态目录下了。减少了维护的麻烦事儿。

猜你喜欢

转载自blog.csdn.net/BASK2312/article/details/131811947
今日推荐