当前位置: 移动技术网 > IT编程>开发语言>Java > SpringBoot实现本地存储文件上传及提供HTTP访问服务的方法

SpringBoot实现本地存储文件上传及提供HTTP访问服务的方法

2020年08月15日  | 移动技术网IT编程  | 我要评论
笔者计划为大家介绍分布式文件系统,用于存储应用的图片、word、excel、pdf等文件。在开始介绍分布式文件系统之前,为大家介绍一下使用本机存储来存放文件资源。二者的核心实现过程是一样的: 上传文

笔者计划为大家介绍分布式文件系统,用于存储应用的图片、word、excel、pdf等文件。在开始介绍分布式文件系统之前,为大家介绍一下使用本机存储来存放文件资源。
二者的核心实现过程是一样的:

  • 上传文件,保存文件(本节是本地磁盘)
  • 返回文件http访问服务路径给前端,进行上传之后的效果展示

一、复习

服务端接收上传的目的是提供文件的访问服务,那么对于springboot而言,有哪些可以提供文件访问的静态资源目录呢?

  • classpath:/meta-inf/resources/ ,
  • classpath:/static/ ,
  • classpath:/public/ ,
  • classpath:/resources/

这是之前我们为大家介绍的内容,从这里看出这里的静态资源都在classpath下。那么就出现问题:

  • 应用的文件资源不能和项目代码分开存储(你见过往github上传代码,还附带项目文件数据的么?)
  • 项目打包困难,当上传的文件越来越多,项目的打包jar越来越大。
  • 代码与文件数据不能分开存储,就意味着文件数据的备份将变得复杂

二、文件上传目录自定义配置

怎么解决上述问题?别忘记了spring boot 为我们提供了使用spring.resources.static-locations配置自定义静态文件的位置。

web:
 upload-path: d:/data/

spring:
 resources:
 static-locations: classpath:/meta-inf/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}
  • 配置web.upload-path为与项目代码分离的静态资源路径,即:文件上传保存根路径
  • 配置spring.resources.static-locations,除了带上spring boot默认的静态资源路径之外,加上file:${web.upload-path}指向外部的文件资源上传路径。该路径下的静态资源可以直接对外提供http访问服务。

三、文件上传的controller实现

详情看代码注释

@restcontroller
public class fileuploadcontroller {

 //绑定文件上传路径到uploadpath
 @value("${web.upload-path}")
 private string uploadpath;
 
 simpledateformat sdf = new simpledateformat("yyyy/mm/dd/");
 
 @postmapping("/upload")
 public string upload(multipartfile uploadfile,
    httpservletrequest request) {

 // 在 uploadpath 文件夹中通过日期对上传的文件归类保存
 // 比如:/2019/06/06/cf13891e-4b95-4000-81eb-b6d70ae44930.png
 string format = sdf.format(new date());
 file folder = new file(uploadpath + format);
 if (!folder.isdirectory()) {
  folder.mkdirs();
 }
 
 // 对上传的文件重命名,避免文件重名
 string oldname = uploadfile.getoriginalfilename();
 string newname = uuid.randomuuid().tostring()
  + oldname.substring(oldname.lastindexof("."), oldname.length());
 try {
  // 文件保存
  uploadfile.transferto(new file(folder, newname));
 
  // 返回上传文件的访问路径
  string filepath = request.getscheme() + "://" + request.getservername()
   + ":" + request.getserverport() + format + newname;
  return filepath;
 } catch (ioexception e) {
  throw new customexception(customexceptiontype.system_error);
 }

 }
}

四、写一个模拟的文件上传页面,进行测试

把该upload.html文件放到classpath:public目录下,对外提供访问。

<!doctype html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>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>

访问测试、点击“选择文件”,之后保存

文件被保存到服务端的web.upload-path指定的资源目录下

浏览器端响应结果如下,返回一个文件http访问路径:

使用该http访问路径,在浏览器端访问效果如下。证明我们的文件已经成功上传到服务端,以后需要访问该图片就通过这个http url就可以了。

到此这篇关于springboot实现本地存储文件上传及提供http访问服务的文章就介绍到这了,更多相关springboot实现文件上传和访问内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网