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

问题

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

上传

此处的范围类型 AjaxResult 是一个继承 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;
    }
}

controller类

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是我自己定义用来存储上传文件的目录名,你可以根据自己的需求来定制。但是需要注意的是在上传的时候也需要是同样的目录名,不然会出现找不到目录的尴尬场面。
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的静态目录下了。减少了维护的麻烦事儿。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
你想了解如何集成使用javamelody-spring-boot-starter和druid-spring-boot-starter吗? 这两个starter都是用于在Spring Boot应用程序进行监控和管理的。要使用它们,您需要将它们添加到应用程序的依赖项。 首先,您需要在pom.xml文件添加以下依赖项以使用javamelody-spring-boot-starter: ``` <dependency> <groupId>net.bull.javamelody</groupId> <artifactId>javamelody-spring-boot-starter</artifactId> <version>1.78.0</version> </dependency> ``` 接下来,您需要添加以下依赖项以使用druid-spring-boot-starter: ``` <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.20</version> </dependency> ``` 一旦您将这些依赖项添加到您的应用程序,您需要在应用程序的配置文件配置它们。例如,如果您使用的是application.properties,请添加以下属性来配置javamelody: ``` javamelody.enabled=true javamelody.storage-directory=monitoring ``` 对于druid,您需要添加以下属性: ``` spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.initialSize=5 spring.datasource.minIdle=5 spring.datasource.maxActive=20 spring.datasource.maxWait=60000 spring.datasource.filters=stat,wall spring.datasource.testWhileIdle=true spring.datasource.validationQuery=SELECT 1 FROM DUAL spring.datasource.testOnBorrow=false spring.datasource.testOnReturn=false spring.datasource.poolPreparedStatements=true spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 ``` 最后,您需要启动应用程序并访问http://localhost:8080/monitoring即可查看javamelody监控页面,而访问http://localhost:8080/druid即可查看druid监控页面。 希望这能帮助您集成使用javamelody-spring-boot-starter和druid-spring-boot-starter。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

讷言丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值