resource下载(springboot下载resource下文件)
一、如何用SpringBoot框架来接收multipart/form-data文件
SpringBoot有它自己的接收请求的代码。下面就给大家详细介绍一下它是如何实现单个文件和多个文件上传的功能的。
首选做一个简单的案例,也就是单个文件上传的案例。(这个案例是基于SpringBoot上面的,所以大家首先得搭建好SpringBoot这个框架)
前台HTML代码:
[html] view plain copy
<html>
<body>
<formaction="/upload"method="POST"enctype="multipart/form-data">
<inputtype="file"name="file"/>
<inputtype="submit"value="Upload"/>
</form>
</body>
</html>
后台接收代码:
[java] view plain copy
/**
*文件上传具体实现方法;
*
*@paramfile
*@return
*/
@RequestMapping("/upload")
@ResponseBody
publicStringhandleFileUpload(@RequestParam("file")MultipartFilefile){
if(!file.isEmpty()){
try{
/*
*这段代码执行完毕之后,图片上传到了工程的跟路径;大家自己扩散下思维,如果我们想把图片上传到
*d:/files大家是否能实现呢?等等;
*这里只是简单一个例子,请自行参考,融入到实际中可能需要大家自己做一些思考,比如:1、文件路径;2、文件名;
*3、文件格式;4、文件大小的限制;
*/
BufferedOutputStreamout=newBufferedOutputStream(
newFileOutputStream(newFile(
file.getOriginalFilename())));
System.out.println(file.getName());
out.write(file.getBytes());
out.flush();
out.close();
}catch(FileNotFoundExceptione){
e.printStackTrace();
return"上传失败,"+e.getMessage();
}catch(IOExceptione){
e.printStackTrace();
return"上传失败,"+e.getMessage();
}
return"上传成功";
}else{
return"上传失败,因为文件是空的.";
}
}
这样就可以实现对multipart/form-data类型文件的接收了。那如果是多个文件外加多个字段呢,下面接着看下一个多个文件上传的案例。
前台HTML界面:
[html] view plain copy
<!DOCTYPEhtml>
<htmlxmlns=""xmlns:th=""
xmlns:sec="">
<head>
<title>HelloWorld!</title>
</head>
<body>
<formmethod="POST"enctype="multipart/form-data"action="/batch/upload">
<p>文件1:<inputtype="text"name="id"/></p>
<p>文件2:<inputtype="text"name="name"/></p>
<p>文件3:<inputtype="file"name="file"/></p>
<p><inputtype="submit"value="上传"/></p>
</form>
</body>
</html>
后台接收代码:
[java] view plain copy
@RequestMapping(value="/batch/upload",method=RequestMethod.POST)
@ResponseBody
publicStringhandleFileUpload(HttpServletRequestrequest){
MultipartHttpServletRequestparams=((MultipartHttpServletRequest)request);
List<MultipartFile>files=((MultipartHttpServletRequest)request)
.getFiles("file");
Stringname=params.getParameter("name");
System.out.println("name:"+name);
Stringid=params.getParameter("id");
System.out.println("id:"+id);
MultipartFilefile=null;
BufferedOutputStreamstream=null;
for(inti=0;i<files.size();++i){
file=files.get(i);
if(!file.isEmpty()){
try{
byte[]bytes=file.getBytes();
stream=newBufferedOutputStream(newFileOutputStream(
newFile(file.getOriginalFilename())));
stream.write(bytes);
stream.close();
}catch(Exceptione){
stream=null;
return"Youfailedtoupload"+i+"=>"
+e.getMessage();
}
}else{
return"Youfailedtoupload"+i
+"becausethefilewasempty.";
}
}
return"uploadsuccessful";
}
这样就可以实现对多个文件的接收了功能了。
二、Springboot打成JAR包后读取外部配置文件
自定义jar目前只能读取application.properties和application.yml吧。可以用一个简单点的方法进行监听注入,在工具包内写一个init方法,在springboot启动时初始化就可以了。比如springboot启动完成后读取配置文件,然后注入到工具包内。
以jar包发布springboot项目时,默认会先使用jar包同级目录下的application.properties来作为项目配置文件。但使用--spring.config.location指定了配置文件,则读取指定的配置文件。
对此,我们可以将springboot项目的配置文件『挪到』jar包之外,然后再启动springboot项目时再指定它使用外部的这些配置文件。
在此处,我们可以使用java-jardemo-0.01-SNAPSHOT来运行项目。正常运行。当我们将其打成jar包时,application.properties同样不会被打包进jar包中。需要另外复制出来和jar包放在才能正常运行。
配置文件SpringBoot使用一个全局的配置文件application.propertiesapplication.yml配置文件的作用:修改SpringBoot自动配置的默认值,SpringBoot在底层都给我们自动配置好。
常规的,在springboot中一般只需要拿appolo或者nacos里配置的属性就够了。
三、SpringBoot 如何优雅读取配置文件10分钟教你搞定
很多时候我们需要将一些常用的配置信息比如阿里云 oss配置、发送短信的相关信息配置等等放到配置文件中。
下面我们来看一下 Spring为我们提供了哪些方式帮助我们从配置文件中读取这些配置信息。
application.yml内容如下:
wuhan2020: 2020年初武汉爆发了新型冠状病毒,疫情严重,但是,我相信一切都会过去!武汉加油!中国加油!my-profile:name: Guide哥email: koushuangbwcx@163.comlibrary:location:湖北武汉加油中国加油books: -name:天才基本法description:二十二岁的林朝夕在父亲确诊阿尔茨海默病这天,得知自己暗恋多年的校园男神裴之即将出国深造的消息——对方考取的学校,恰是父亲当年为她放弃的那所。 -name:时间的秩序description:为什么我们记得过去,而非未来?时间“流逝”意味着什么?是我们存在于时间之内,还是时间存在于我们之中?卡洛·罗韦利用诗意的文字,邀请我们思考这一亘古难题——时间的本质。 -name:了不起的我description:如何养成一个新习惯?如何让心智变得更成熟?如何拥有高质量的关系?如何走出人生的艰难时刻?
1.通过@value读取比较简单的配置信息
使用@Value("${property}")读取比较简单的配置信息:
@Value("${wuhan2020}")String wuhan2020;
需要注意的是@value这种方式是不被推荐的,Spring比较建议的是下面几种读取配置信息的方式。
2.通过@ConfigurationProperties读取并与 bean绑定
LibraryProperties类上加了@Component注解,我们可以像使用普通 bean一样将其注入到类中使用。
importlombok.Getter;importlombok.Setter;importlombok.ToString;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.context.annotation.Configuration;importorg.springframework.stereotype.Component;importjava.util.List;@Component@ConfigurationProperties(prefix="library")@Setter@Getter@ToStringclassLibraryProperties{privateString location;privateList books;@Setter@Getter@ToStringstaticclassBook{ String name; String description; }}
这个时候你就可以像使用普通 bean一样,将其注入到类中使用:
packagecn.javaguide.readconfigproperties;importorg.springframework.beans.factory.InitializingBean;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;/***@authorshuang.kou*/@SpringBootApplicationpublicclassReadConfigPropertiesApplicationimplementsInitializingBean{privatefinalLibraryProperties library;publicReadConfigPropertiesApplication(LibraryProperties library){this.library= library; }publicstaticvoidmain(String[] args){ SpringApplication.run(ReadConfigPropertiesApplication.class,args); }@OverridepublicvoidafterPropertiesSet(){ System.out.println(library.getLocation()); System.out.println(library.getBooks()); }}
控制台输出:
湖北武汉加油中国加油[LibraryProperties.Book(name=天才基本法, description........]
3.通过@ConfigurationProperties读取并校验
我们先将application.yml修改为如下内容,明显看出这不是一个正确的 email格式:
my-profile:name: Guide哥email: koushuangbwcx@
ProfileProperties类没有加@Component注解。我们在我们要使用ProfileProperties的地方使用@
EnableConfigurationProperties注册我们的配置 bean:
importlombok.Getter;importlombok.Setter;importlombok.ToString;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.stereotype.Component;importorg.springframework.validation.annotation.Validated;importjavax.validation.constraints.Email;importjavax.validation.constraints.NotEmpty;/***@authorshuang.kou*/@Getter@Setter@ToString@ConfigurationProperties("my-profile")@ValidatedpublicclassProfileProperties{@NotEmptyprivateString name;@Email@NotEmptyprivateString email;//配置文件中没有读取到的话就用默认值privateBooleanhandsome=Boolean.TRUE;}
具体使用:
packagecn.javaguide.readconfigproperties;importorg.springframework.beans.factory.InitializingBean;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.boot.context.properties.EnableConfigurationProperties;/***@authorshuang.kou*/@SpringBootApplication@EnableConfigurationProperties(ProfileProperties.class)publicclassReadConfigPropertiesApplicationimplementsInitializingBean{privatefinalProfileProperties profileProperties;publicReadConfigPropertiesApplication(ProfileProperties profileProperties){this.profileProperties= profileProperties; }publicstaticvoidmain(String[] args){ SpringApplication.run(ReadConfigPropertiesApplication.class,args); }@OverridepublicvoidafterPropertiesSet(){ System.out.println(profileProperties.toString()); }}
因为我们的邮箱格式不正确,所以程序运行的时候就报错,根本运行不起来,保证了数据类型的安全性:
Binding to target org.springframework.boot.context.properties.bind.BindException:Failedtobindpropertiesunder'my-profile'to cn.javaguide.readconfigproperties.ProfileProperties failed:Property:my-profile.emailValue:koushuangbwcx@Origin:classpathresource[application.yml]:5:10Reason:mustbeawell-formedemailaddress
我们把邮箱测试改为正确的之后再运行,控制台就能成功打印出读取到的信息:
ProfileProperties(name=Guide哥, email=koushuangbwcx@163.com, handsome=true)
4.@PropertySource读取指定 properties文件
importlombok.Getter;importlombok.Setter;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.context.annotation.PropertySource;importorg.springframework.stereotype.Component;@Component@PropertySource("classpath:website.properties")@Getter@SetterclassWebSite{@Value("${url}")privateString url;}
使用:
@Autowiredprivate WebSite webSite;System.out.println(webSite.getUrl());//
5.题外话:Spring加载配置文件的优先级
Spring读取配置文件也是有优先级的,直接上图:
原文链接: