springboot单个文件上传及解决图片上传后需要重启服务器才能刷新图片

前话

前面逛论坛发现很多人写springboot文件上传遇到很多bug,索性我也来写个简单的springboot文件上传小demo。直接上代码吧。

upload.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>

</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="uploadFile" value="请选择文件">
    <input type="submit" value="上传">
</form>

</body>
</html>

这里注意一下 enctype="multipart/form-data"就好了

JsonData
public class JsonData {
    //状态码
    private  int code;
    //返回信息
    private String msg;
    //访问路径
    private String  url;

    public JsonData(int code, String msg, String url) {
        this.code = code;
        this.msg = msg;
        this.url = url;
    }

    public int getCode() {

        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}
application.properties
#端口号
server.port=10002
#单个文件最大上传大小
spring.servlet.multipart.max-file-size=1MB
#多个文件上传总文件最大大小
spring.servlet.multipart.max-request-size=100MB
#文件上传路径
web.upload-path=C:/Users/Administrator/Desktop/
#将文件路径加载到默认静态配置中  这样就可以直接访问文件路径下的资源
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/test/,file:${web.upload-path} 
UploadController
@RestController
public class UploadController {
    //private  static   String  filePath="C:/Users/Administrator/Desktop/";
    //默认注入application.properties里的对应值
    @Value("${web.upload-path}")
    private    String  filePath;
    @RequestMapping(value = "upload")
    @ResponseBody
    public JsonData upload(@RequestParam("uploadFile") MultipartFile file,HttpServletRequest request) {

        //file.isEmpty(); 判断图片是否为空
        //file.getSize(); 图片大小进行判断
        // 获取文件名
        String fileName = file.getOriginalFilename();
        System.out.println("上传的文件名为:" + fileName);
        // 获取文件的后缀名,比如图片的jpeg,png
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("上传的后缀名为:" + suffixName);
        // 文件上传后的路径
        fileName = UUID.randomUUID() + suffixName;
        System.out.println("转换后的名称:"+fileName);
        File dest = new File(filePath + fileName);
        //文件上传路径
        System.out.println("filepath:"+filePath);
        //文件路径
        System.out.println("dest:"+dest);
        try {
            //存储文件
            file.transferTo(dest);
            //返回访问路径
            String  url=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/"+fileName;
            System.out.println("url:"+url);
            //返回成功结果
            return new JsonData(0,"上传成功",url);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();

        }
        //返回失败结果
        return  new JsonData(-1, "上传失败", null);
    }

}
测试结果

返回信息:
在这里插入图片描述

访问结果
在这里插入图片描述

特意尝试一下将文件存储到项目的static/images下

更改了application.properties以下两个信息

//private  static   String  filePath="C:/Users/Administrator/Desktop/";
//@Value("${web.upload-path}")
private    String  filePath="D:\\Java学习\\springboot小滴\\springboot项目\\upload\\src\\main\\resources\\static\\images\\";
...........................................
//返回访问路径
String  url=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/images/"+fileName;
果然它出现了

返回结果:
在这里插入图片描述
访问结果
在这里插入图片描述
重启一下项目后
在这里插入图片描述
思考了一下
关于图片上传后需要重启服务器才能刷新图片
这是一种保护机制,为了防止绝对路径被看出来,目录结构暴露
解决方法:将虚拟路径/images/
向绝对路径 (D:\Java学习\springboot小滴\springboot项目\upload\src\main\resources\static\images\)映射

解决方法
配置一个webConfig类
webConfig

@Configuration
public class webConfig implements WebMvcConfigurer {
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("配置文件已经生效");
        //关于图片上传后需要重启服务器才能刷新图片
        //这是一种保护机制,为了防止绝对路径被看出来,目录结构暴露
        //解决方法:将虚拟路径/images/
        //        向绝对路径 (D:\\Java学习\\springboot小滴\\springboot项目\\upload\\src\\main\\resources\\static\\images\\)映射

       String path="D:\\Java学习\\springboot小滴\\springboot项目\\upload\\src\\main\\resources\\static\\images\\";
       registry.addResourceHandler("/images/**").addResourceLocations("file:"+path);


        }
    }

后续就正常啦

总结一下:

最开始的文件上传方式不论是在ide中还是打成jar包都能够正常运行,文件都会存储到配置文件中设置的路径中。后面更改的上传方式在打包运行时可能会因为上传文件夹不存在而产生异常。

  • 18
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值