springboot(八):springboot文件上传、静态资源映射
1.静态资源
2.测试
启动程序后访问:http://localhost:8080/test/img/timg.jpg
3.直接访问
如果直接访问:可以得到图片http://localhost:8080/img/timg.jpg ,但是这样做无疑暴露了真实的地址。
4.定义***拦截/img/*
***代码:
package com.qianliu.springboot_test.interceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component //@Component标签相当于配置文件中的<bean id="" class=""/>,以后可以直接放入到@Configuration标注的类中
public class SimpleIntercepter implements HandlerInterceptor {
//获取日志
private Logger logger = LoggerFactory.getLogger(this.getClass());
/* * 进入controller层之前拦截请求 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//含有"/img/"的链接进行拦截
if(request.getRequestURI().startsWith("/img/")){
return false;
}
return true;
}
/* * 处理请求完成后视图渲染之前的处理操作 */
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
logger.info("postHandle..................");
}
/* * 视图渲染之后的操作 */
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
logger.info("afterCompletion...............");
}
}
添加***到配置文件中
package com.qianliu.springboot_test.interceptor.configuration;
import com.qianliu.springboot_test.interceptor.SimpleIntercepter;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
/* * @author qianliu on 2019/5/16 21:43 * @Discription:注册SimpleIntercepter***并注册拦截的url */
@Configuration //SimpleIntercepter相当于一个Bean,因为它被@Component标注过
public class UserInterceptorAppConfig implements WebMvcConfigurer {
@Resource
SimpleIntercepter simpleIntercepter;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(simpleIntercepter).addPathPatterns("/**"); //该***使用在所有的url上
}
}
5.测试
访问:http://localhost:8080/test/img/timg.jpg
访问:http://localhost:8080/img/timg.jpg
6.上传文件的界面
7.配置需要上传的本地仓库的url
8.上传文件的controller
package com.qianliu.springboot_test.controller;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.UUID;
@Controller
public class UploadController {
//获取日志生成器
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${file.uploadFolder}")
private String uploadPath; //文件上传的地址
@RequestMapping(value = "/hello" , method = RequestMethod.GET)
@ResponseBody
public String hello(){
return "hello";
}
/** * 初始化上传文件界面,跳转到index.jsp * @return */
@RequestMapping(value = "/index" , method = RequestMethod.GET)
public String index(){
return "index";
}
/** * 上传多个文件 * @param file 上传文件集合 * @return */
@RequestMapping(value = "/uploads",method = RequestMethod.POST)
@ResponseBody
public HashMap uploads(MultipartFile[] file, HttpSession session)
{
//上传目录地址
String uploadDir = uploadPath;
//如果目录不存在,自动创建文件夹
File dir = new File(uploadDir);
if(!dir.exists())
{
dir.mkdir();
logger.info("创建文件:"+uploadDir);
}
String suffix = null;
String fileName = null;
HashMap hashMap = new HashMap();
try {
//遍历文件数组执行上传
for (int i =0;i<file.length;i++) {
if(file[i] != null) {
logger.info("开始上传文件.......");
//调用上传方法
suffix = file[i].getOriginalFilename().substring(file[i].getOriginalFilename().lastIndexOf(".")); //后缀名
fileName = UUID.randomUUID() + suffix;
IOUtils.copy(file[i].getInputStream(),new FileOutputStream(uploadDir+"\\"+fileName));
//file[i].transferTo(new File(uploadDir+"\\"+fileName));
logger.info("上传"+uploadDir+"\\"+fileName+"文件成功!");
}
}
logger.info("上传结束!所有文件上传文件至:"+uploadDir);
}catch (Exception e)
{
//打印错误堆栈信息
e.printStackTrace();
logger.info("上传文件失败!");
hashMap.put("uploadMessage","上传失败");
return hashMap;
}
hashMap.put("uploadMessage:","上传成功");
return hashMap;
}
}
9.测试
本地生成文件成功