SpringBoot實戰之文件上傳下載及攔截器(六)

文件上傳下載

1. 文件上傳
1.1 準備上傳頁面
<form action="路徑...." method="post" enctype="multipart/form-data">
        <input type="file" name="aa">
        <input type="submit" value="上傳">
</form>
<!--
	1. 表單提交方式必須是post
	2. 表單的enctype屬性必須爲multipart/form-data
	3. 後臺接受變量名字要與文件選擇name屬性一致
-->
1.2 編寫控制器
@Controller
@RequestMapping("/file")
public class FileController {
  @RequestMapping("/upload")
  public String upload(MultipartFile aa, HttpServletRequest request) throws IOException {
        String realPath = request.getRealPath("/upload");
        aa.transferTo(new File(realPath,aa.getOriginalFilename()));//文件上傳
        return "index";
  }
}
1.3 修改文件上傳大小

#上傳時出現如下異常:  上傳文件的大小超出默認配置  默認10M
nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (38443713) exceeds the configured maximum (10485760)
#修改上傳文件大小:
spring:
  http:
    multipart:
      max-file-size: 209715200 #單位是字節

2. 文件下載
2.1 提供下載文件鏈接
<a href="../file/download?fileName=corejava.txt">corejava.txt</a>
2.2 開發控制器
@RequestMapping("/download")
public void download(String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String realPath = request.getRealPath("/upload");
        FileInputStream is = new FileInputStream(new File(realPath, fileName));
        ServletOutputStream os = response.getOutputStream();
        response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
        IOUtils.copy(is,os);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }

攔截器

1. 開發攔截器
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        System.out.println("======1=====");
        return true;//返回true 放行  返回false阻止
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("=====2=====");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
        System.out.println("=====3=====");
    }
}
2. 配置攔截器
@Component
public class InterceptorConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //添加攔截器
        registry.addInterceptor(new MyInterceptor())
            .addPathPatterns("/**")//定義攔截路徑
            .excludePathPatterns("/hello/**"); //排除攔截路徑
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章