好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

SpringBoot上传文件到本服务器 目录与jar包同级问题

前言

看标题好像很简单的样子,但是针对使用 jar 包发布springboot项目就不一样了。
当你使用tomcat发布项目的时候, 上传文件 存放会变得非常简单,因为你可以随意操作项目路径下的资源。但是当你使用springboot的jar包发布项目的时候,你会发现,你不能像以前一样操作文件了。当你使用file file = new file()的时候根本不知道这个路径怎么办。而且总不能很小的项目也给它构建一个文件 服务器 吧。所以这次就来解决这样的问题。
不想知道细节的,可以直接跳转到最后封装的部分,里面有相应的实现。

原因

其实原因你也想的到,你无法对jar包里面的资源进行操作,而对于springboot项目来说,你只能读取里面的文件,只能使用inputstream。使用如下方式针对资源文件进行读取:

?

1

2

classpathresource classpathresource = new classpathresource( "static/a.txt" );

classpathresource.getinputstream();

其中,这个a.txt存放在resources/static目录下

通过上述方式可以获取a中的内容

实现

因为我们无法操作jar包内容,所以我们只能将文件存放在别的位置,与jar包同级的目录是一个不错的选择。

首先获取根目录

?

1

2

3

4

file path = new file(resourceutils.geturl( "classpath:" ).getpath());

if (!path.exists()) {

path = new file( "" );

}

然后获取需要的目录,我们设定我们需要将文件存放在与jar包同级的static的upload目录下

?

1

2

3

4

file upload = new file(path.getabsolutepath(), "static/upload/" );

if (!upload.exists()) {

upload.mkdirs();

}

然后当我们要将上传的文件存储的时候,按照下面的方式去新建文件,然后使用你喜欢的方式进行存储就可以了。

?

1

2

file upload = new file(path.getabsolutepath(), "static/upload/test.jpg" );

fileutils.copyinputstreamtofile(inputstream, uploadfile);

不要忘记

你需要在application.yml配置中加入以下代码,指定两个静态资源的目录,这样你上传的文件就能被外部访问到了。

?

1

2

3

4

spring:

# 静态资源路径

resources:

static -locations: classpath: static /,file: static /

这样就能实现上传文件

最后的封装

工具类:

https://github.com/linkinstars/springboottemplate/blob/master/src/main/java/com/linkinstars/springboottemplate/util/filehandleutil.java

这个工具类依赖了

?

1

2

compile group: 'commons-fileupload' , name: 'commons-fileupload' , version: '1.3.1'

compile group: 'commons-io' , name: 'commons-io' , version: '2.4'

如何你不喜欢完全可以根据自己的喜欢改变

如何使用:

?

1

2

3

4

5

6

7

8

/**

* 测试文件上传

*/

@requestmapping ( "/upload" )

@responsebody

public string upload(multipartfile file) throws ioexception {

return "文件存放路径为" + filehandleutil.upload(file.getinputstream(), "image/" , file.getoriginalfilename());

}

最后效果


follow up

这个工具类只是实现了如何上传文件,入参也只有inputstream,后续如何你需要接入参数file或者加入文件名防重复等等,就由你来完成了。

总结

以上所述是小编给大家介绍的springboot上传文件到本服务器 目录与jar包同级问题,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

原文链接:http://www.cnblogs.com/linkstar/p/9938721.html

查看更多关于SpringBoot上传文件到本服务器 目录与jar包同级问题的详细内容...

  阅读:16次