欢迎访问 生活随笔!

凯发k8官方网

当前位置: 凯发k8官方网 > 前端技术 > javascript >内容正文

javascript

一篇文章教你学会使用springboot实现文件上传和下载 -凯发k8官方网

发布时间:2025/1/21 javascript 15 豆豆
凯发k8官方网 收集整理的这篇文章主要介绍了 一篇文章教你学会使用springboot实现文件上传和下载 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

文章目录

      • 一、搭建springboot开发环境
        • 1、创建项目
        • 2、配置application.properties参数
        • 3、实体响应类和异常信息类
        • 4、创建filecontroller
      • 二、接口测试
        • 1、在完成上述的代码之后运行程序,运行完成之后就可以使用postman进行测试了。
        • 2,测试下载文件
      • 三、使用web网页上传

写在前面: 我是「境里婆娑」。我还是从前那个少年,没有一丝丝改变,时间只不过是考验,种在心中信念丝毫未减,眼前这个少年,还是最初那张脸,面前再多艰险不退却。
写博客的目的就是分享给大家一起学习交流,如果您对 java感兴趣,可以关注我,我们一起学习。

前言:上篇文章 一篇文章教你学会java基础i/o流 我们已经对i/o流有了一定了解,在这里中,您将学习如何使用spring boot实现web服务中的文件上传和下载功能。首先会构建一个rest api实现上传及下载的功能,然后使用postman工具来测试这些接口,最后创建一个web界面,如果对springboot不熟悉的话可以看这篇文章: springboot系列文章

导语本文主要讲解:

一、搭建springboot开发环境

1、创建项目

开发环境为intellij idea,项目创建很简单,按照以下的步骤创建即可:

  • file -> new -> project
  • 选择 spring initializr,点击 next
  • 填写 group (项目域名) 和 artifact (项目别名)
  • 构建类型可以选择 maven
  • 添加 web 依赖
  • 输入项目名称及保存路径,完成创建

如果觉得上面看着不直观,可以看下面的gif图整个创建过程。

项目创建完毕就可以开发,项目的整体结构如下所示:

2、配置application.properties参数

项目创建完成之后,需要在application.properties中添加以下参数:

server.port=8080 ## multipart (multipartproperties) # 开启 multipart 上传功能 spring.servlet.multipart.enabled=true # 文件写入磁盘的阈值 spring.servlet.multipart.file-size-threshold=2kb # 最大文件大小 spring.servlet.multipart.max-file-size=200mb # 最大请求大小 spring.servlet.multipart.max-request-size=215mb # 文件存储所需参数 # 所有通过 rest api 上传的文件都将存储在此目录下 file.upload.path=d:/aplus

其中file.upload.path =d:/aplus参数为自定义的参数,有两种方式可以获取到此参数

  • 使用@value("${file.upload.path}")
  • 使配置参数可以自动绑定到pojo类。

使配置参数绑定实体类详细代码如下:

/*** @author zhaosl* @projectname springboot-upload* @date 2020/6/3 23:51*/ @configurationproperties(prefix = "file") public class fileproperty {private string filepath;public string getfilepath() {return filepath;}public void setfilepath(string filepath) {this.filepath = filepath;} }

敲黑板这是重点如果想要此配置性能必须在@springbootuploadapplication注解的类中添加@enableconfigurationproperties注解以开启configurationproperties功能。

springbootuploadapplication启动类

@springbootapplication @enableconfigurationproperties({fileproperty.class }) public class springbootuploadapplication {public static void main(string[] args) {springapplication.run(springbootuploadapplication.class, args);}}

3、实体响应类和异常信息类

文件成功后需要有的响应实体类uploadfileresponse和文件出现上传异常类fileexception来处理异常信息

响应实体类uploadfileresponse

/*** @author zhaosl* @projectname springboot-upload* @date 2020/6/3 23:58*/ public class uploadfileresponse {private string filename;private string filedownloaduri;private string filetype;private long size;public uploadfileresponse() {}public uploadfileresponse(string filename, string filedownloaduri, string filetype, long size) {this.filename = filename;this.filedownloaduri = filedownloaduri;this.filetype = filetype;this.size = size;}//get set 省略

异常信息类fileexception

/*** @author zhaosl* @projectname springboot-upload* @date 2020/6/4 0:04*/ public class fileexception extends runtimeexception {public fileexception(string message) {super(message);}public fileexception(string message, throwable cause) {super(message, cause);} }

4、创建filecontroller

创建文件上传下载所需的rest api接口

/*** @author shuliangzhao* @projectname springboot-upload* @date 2020/6/3 23:34*/ @restcontroller public class filecontroller {private static final logger logger = loggerfactory.getlogger(filecontroller.class);@autowiredprivate fileservice fileservice;@postmapping("/uploadfile")public uploadfileresponse uploadfile(@requestparam("file") multipartfile file){string filename = fileservice.storefile(file);string filedownloaduri = servleturicomponentsbuilder.fromcurrentcontextpath().path("/downloadfile/").path(filename).touristring();return new uploadfileresponse(filename, filedownloaduri,file.getcontenttype(), file.getsize());}@postmapping("/uploadmultiplefiles")public list<uploadfileresponse> uploadmultiplefiles(@requestparam("files") multipartfile[] files) {list<uploadfileresponse> list = new arraylist<>();if (files != null) {for (multipartfile multipartfile:files) {uploadfileresponse uploadfileresponse = uploadfile(multipartfile);list.add(uploadfileresponse);}}return list;//简单写法/* return arrays.stream(files).map(this::uploadfile).collect(collectors.tolist());*/}@getmapping("/downloadfile/{filename:.*}")public responseentity<resource> downloadfile(@pathvariable string filename, httpservletrequest request) {resource resource = fileservice.loadfileasresource(filename);string contenttype = null;try {request.getservletcontext().getmimetype(resource.getfile().getabsolutepath());} catch (ioexception e) {logger.info("could not determine file type.");}if(contenttype == null) {contenttype = "application/octet-stream";}return responseentity.ok().contenttype(mediatype.parsemediatype(contenttype)).header(httpheaders.content_disposition, "attachment; filename=\"" resource.getfilename() "\"").body(resource);}}

filecontroller类收到请求后,调用fileservice类的storefile()方法将文件写入到系统中进行存储,其存储目录就是之前在application.properties配置文件中的file.upload.path参数的值。

下载接口downloadfile()在收到用户请求之后,使用fileservice类提供的loadfileasresource()方法获取存储在系统中文件并返回文件供用户下载。

fileservice实现类为:

/*** @author shuliangzhao* @projectname springboot-upload* @date 2020/6/3 23:34*/ @component public class fileservice {private path filestoragelocation; // 文件在本地存储的地址public fileservice( @value("${file.upload.path}") string path) {this.filestoragelocation = paths.get(path).toabsolutepath().normalize();try {files.createdirectories(this.filestoragelocation);} catch (ioexception e) {throw new fileexception("could not create the directory", e);}}/*** 存储文件到系统* @param file 文件* @return 文件名*/public string storefile(multipartfile file) {// normalize file namestring filename = stringutils.cleanpath(file.getoriginalfilename());try {// check if the file's name contains invalid charactersif(filename.contains("..")) {throw new fileexception("sorry! filename contains invalid path sequence " filename);}// copy file to the target location (replacing existing file with the same name)path targetlocation = this.filestoragelocation.resolve(filename);files.copy(file.getinputstream(), targetlocation, standardcopyoption.replace_existing);return filename;} catch (ioexception ex) {throw new fileexception("could not store file " filename ". please try again!", ex);}}public resource loadfileasresource(string filename) {try {path filepath = this.filestoragelocation.resolve(filename).normalize();resource resource = new urlresource(filepath.touri());if(resource.exists()) {return resource;} else {throw new fileexception("file not found " filename);}} catch (malformedurlexception ex) {throw new fileexception("file not found " filename, ex);}} }

二、接口测试

1、在完成上述的代码之后运行程序,运行完成之后就可以使用postman进行测试了。

单个文件上传调用接口为:http://localhost:8080/uploadfile
gif图如下所示:

返回结果为:

{"filename": "1519897877-lngupqgbki.jpg","filedownloaduri": "http://localhost:8080/downloadfile/1519897877-lngupqgbki.jpg","filetype": "image/jpeg","size": 25294 }

多个文件上传调用接口为:http://localhost:8080/uploadmultiplefiles
gif图如下所示:

返回结果为:

[{"filename": "8~}1oc59zka0)`[pi_nu[qk.png","filedownloaduri": "http://localhost:8080/downloadfile/8~}1oc59zka0)`[pi_nu[qk.png","filetype": "image/png","size": 1525371},{"filename": "1519897877-lngupqgbki.jpg","filedownloaduri": "http://localhost:8080/downloadfile/1519897877-lngupqgbki.jpg","filetype": "image/jpeg","size": 25294} ]

2,测试下载文件

在浏览器中输入网址:http://localhost:8080/downloadfile/1519897877-lngupqgbki.jpg

会把文件下载下来如下所示:

三、使用web网页上传

增加thymeleaf前端解析器依赖,使springboot工程可以访问html网页

<dependency><groupid>org.springframework.boot</groupid><artifactid>spring-boot-starter-thymeleaf</artifactid></dependency>

** thymeleaf视图解析器配置增加到配置文件中**

#在构建url时添加到视图名称前的前缀(默认值:classpath:/templates/) spring.thymeleaf.prefix=classpath:/templates/ # 在构建url时附加到视图名称的后缀。 spring.thymeleaf.suffix=.html

新建的index.html网页

<!doctype html> <html lang="en"> <head><meta charset="utf-8"><title>文件上传</title> </head> <body> <form method="post" action="/uploadfile" enctype="multipart/form-data"><input type="file" name="file"><br><br><input type="submit" value="提交"> </form> </body> </html>

增加访问的index.html网页控制器

/*** @author shuliangzhao* @projectname springboot-upload* @date 2020/6/4 23:29*/ @controller public class indexcontroller {@getmapping("/")public string index() {return "index";} }

启动项目访问凯发k8官方网首页开始上传文件如下所示:

到此文件的上传及下载功能已完成。在正式环境中可能还需要将上传的文件路径保存到数据库,到时候可以根据需要做处理。

本文来源代码: https://github.com/fadehub/springboot-upload
—————————————————————————————————
由于本人水平有限,难免有不足,恳请各位大佬不吝赐教!

总结

以上是凯发k8官方网为你收集整理的一篇文章教你学会使用springboot实现文件上传和下载的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得凯发k8官方网网站内容还不错,欢迎将凯发k8官方网推荐给好友。

网站地图