一、静态资源配置
1、静态资源的配置信息
在application.properties文件中需要配置两个属性信息,分别是:spring.resources.static-locations与spring.mvc.static-path-pattern;其中spring.resources.static-locations对应静态资源文件在jar包或者war包中的实际路径(相对路径);spring.mvc.static-path-pattern则代表了相应资源的实际url路径;该URL路径可能和js及HTML中访问的路径不一致,实力配置如下示意:
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/, classpath:/static/,classpath:/public/
spring.mvc.static-path-pattern=/static/**
2、在spring boot中配置静态资源,在 2.0版本需要继承WebMvcConfigurationSupport对象,重写addResourceHandlers方法,在该方法中添加静态资源处理器(实际上就是将静态资源路径映射到相应的文件目录中),示例代码如下:
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/js/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/js/");
registry.addResourceHandler("/css/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/css/");
registry.addResourceHandler("/html/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/html/");
registry.addResourceHandler("/img/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/img/");
super.addResourceHandlers(registry);
}
其中registry.addResourceHandler("/js/**")中映射的路径为html或者js中引用的静态资源路径,而addResourceLocations方法将组合spring.resources.static-locations中配置的属性信息与该方法参数中传递的路径生成静态资源实际路径。
二、文件数据下载
文件下载的时候一般通过路径参数指定下载文件的名称,程序获得路径参数后到相应的文件保存目录中读取文件写入到应答流(response),示例代码如下:
/*
采用SPEL方式来表达路径,以消除不能获取文件扩展名的问题
*/
@RequestMapping("/{name:.+}")
public void DownloadFile(HttpServletRequest request, HttpServletResponse response, @PathVariable("name") String fileName)
{
logging.debug("the URL is "+request.getRequestURL());
if (isFileValid(fileName))
{
String downloadFile=fileRootPath+fileName;
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
FileInputStream inStream=null;
BufferedInputStream bufferInStream=null;
try {
ServletOutputStream outStream=response.getOutputStream();
inStream=new FileInputStream(downloadFile);
bufferInStream=new BufferedInputStream(inStream);
byte[] buffer=new byte[BUFFER_LENGTH];
int len=-1;
while ( (len=bufferInStream.read(buffer))>0)
{
outStream.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}
finally
{
if (bufferInStream!=null) {
try {
bufferInStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inStream!=null)
{
try {
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
protected boolean isFileValid(String fileName)
{
if (fileName.isEmpty() || fileName==null || fileName.compareTo("")==0)
return false;
String downloadFile=fileRootPath+fileName;
File file = new File(downloadFile);
if (file.exists())
return true;
else
return false;
}
因为下载的文件有扩展名,需要采用spel 方式对路径变量参数特别说明
三 、上传文件
示例代码如下示意:
//=================添加produces是为了防止出现乱码,表示返回json格式的数据,编码格式为utf-8=============
@RequestMapping(value="/fileload",method = RequestMethod.POST,produces = { "application/json;charset=UTF-8" })
@ResponseBody
public String LoadFiles(HttpServletRequest request,HttpServletResponse response)
{
String echoMessage="文件上传成功";
final Boolean error=false;
request.getParameterMap().forEach((key,value)->{
if (value instanceof String[])
{
for (String val:value)
{
logging.debug("the key is "+key+",the value is :"+val);
}
}
else
logging.debug("the key is "+key+",the value is :"+value);
});
if (request instanceof MultipartHttpServletRequest)
{
try
{
((MultipartHttpServletRequest) request).getMultiFileMap().forEach((key,mfiles)->{
logging.debug("the key is :"+key);
mfiles.forEach((mfile)->{
String fName=mfile.getOriginalFilename();
byte[] files;
try {
files = mfile.getBytes();
WriteLoadFile(fName,files);
} catch (IOException e) {
e.printStackTrace();
logging.debug(e.getMessage());
//===============如果需要将lambda中的异常掷出,需要将异常更新为运行时异常=====
throw new RuntimeException(e.getCause());
}});
});
}
catch (RuntimeException ee) {
logging.debug("lambda run error:"+ee.getMessage());
}
}
return echoMessage;
}
protected void WriteLoadFile(String fileName,byte[] fileCont) throws IOException {
if (fileName.isEmpty() || fileName.compareTo("")==0 || fileName==null)
return;
String outputName=OUTPUT_PATH+fileName;
File file=new File(outputName);
if (file.exists())
file.delete();
FileOutputStream outputStream=new FileOutputStream(outputName);
BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(outputStream) ;
try {
bufferedOutputStream.write(fileCont);
}
finally {
outputStream.close();
outputStream.close();
}
}
因为上传后返回信息有可能出现中文,为避免出现乱码,需要为RequestMapping注解添加属性produces = { "application/json;charset=UTF-8" }