SpringMVC的文件上传和下载

半城伤御伤魂 提交于 2020-02-07 06:55:36
        这个部分主要分成三块,文件上传,文件下载,拦截器;
        文件上传和下载好理解,但是拦截器的主要功能还是说你在进行登录的时候,假如你还没登录,然后就跳主页的话,就会把你给拦截下来;下面开始文件上传的功能描述;
        为了能上传文件,必须将表单里的method设置为POST,并将enctype设置为multipart/form-data;只有在这种情况下,浏览器才会把用户选择的文件二进制数据发送给服务器;
        下面是实例;
<html>
    <body>
        <form action = "upload" enctype = "multipart/form-data" method = "post">
            <table>
                <tr>
                    <td>文件描述:</td>
                    <td><input type = "text" name  = "desctiption"></td>
                </tr>
                <tr>
                    <td>请选择文件:</td>
                    <td><input type = "text" name = "file"></td>
                </tr>
                <tr>
                    <td><input type = "submit" value = "上传"></td>
                </tr>
            </table>
        </form>
    </body>
</html>

   然后我们要来一个Controller控制器来接受处理一下文件;

@RequestMapping(value = "/upload",method = RequestMethod.POST)
public String upload(HttpServletRequest request,
                    @RequestParam("description") String description,
                    @RequestParam("file") MultipartFile file) throws Exception{
        System.out.println(description);
        if(!file.isEmpty()){
            String path = request.getServletContext().getRealPath("/images");
            String filename = file.getOriginalFilename();
            File filepath = new File(path,filename);
            if(!filepath.getParentFile().exists()){
                filepath.getParentFile().mkdirs();
            }
            file.transferTo(new File(path + File.separator + filename));
            return "success";
        }else {
            return "error";
        }
}

          而我们知道在SpringMVC上下文中默认没有装配MultipartResolver,因此默认情况下其不能处理文件上传工作,如果想使用Spring的文件上传功能,则需要在上下文中配置MultipartResolver;springmvc-config.xml;

<bean id = "multipartResolver"
      class = "org.springframework.web.multipart.commons.CommonsMultipartResolver">
      <property name = "maxUploadSize">
          <value>10485760</value>
      </property>
      <property name = "defaultEncoding">
          <value>UTF-8</value>
      </property>
</bean>

  

需要注意的是,CommonsMultipartResolver必须依赖于Apache CommonsFileUpload的组件,所以需要将Apache的Commons FileUpload的jar包放到项目的类路径下;
    另外还有一种上传文件的方式,就是使用接受上传文件,也就是说我们把二进制文件作为一个POJO模型对象来接收上传的文件;
上传文件的jsp页面跟前面一样;在POJO的模型数据时如下;
public class User implements Serializable{
    private String username;
    private MultipartFile image;
    //省略set/get方法;
}

  下面是控制器的代码;

@RequestMapping(value = "/register")
public String register(HttpServletReqeust request,
                      @ModelAttribute User user,
                      Model model) throws Exception{
        System.out.println(user.getUsername());
    if(!user.getImage().isEmpty()){
        String path = request.getServletContext().getRealPath("/images");
        String filename = user.getImage().getOriginalFilename();
        File filepath = new File(path,filename);
        if(!filepath.getParentFile().exists()){
            filepath.getParentFile().mkdirs();
        }
        user.getImage().transferTo(new File(path + File.separator + filename));
        model.addAttribute("user",user);
        return "userInfo";
    }else {
        return "error";
    }
}

  

<h3>文件下载</h3>
<a href = "download?filename = ${requestScope.user.image.originalFilename}">
    ${requestScope.user.image.originalFilename}</a>

  文件下载;代码如下;

@ReqeustMapping(value = "/download")
public ResponseEntity<byte[]> download(HttpServletRequest request,
                              @RequestParam("filename") String filename,
                              Model mode){
        String path = request.getServletContext().getRealPath("/images");
        File file = new File(path + File.separator + filename);
        HttpHeaders headers = new HttpHeaders();
    String downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
    headers.setContentDispositionFormData("attachment",downloadFileName);
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStaus.CREATED);
}

  Interceptor拦截器也是SpringMVC中相当重要的功能,它的主要作用是拦截用户的请求,并进行相应的处理,比如通过拦截器来进行用户权限验证,或者用来判断用户是否已经登录等;我们需要做的就是先定义一个拦截器,然后通过XML文件配置来把接口设置进去;

public class AuthorizationInterceptor implements HandlerInterceptor{
    private static final String[] IGNORE_URI = {"/loginForm","login"};
    @Override 
    public void afterCompletion(HttpServletRequest,
                        HttpServletResponse response,Object handler,Exception exception) throws Exception{
            System.out.println("AuthorizationInterceptor afterCompletion -- >");
    }
    @Override 
    public void postHandle(HttpServletRequest request,HttpServletResponse response,
                          Object handler,ModelAndView mv) throws Exception{
        System.out.println("AuthorizationInterceptor postHandle -- >");
    }
    @Override
    public boolean preHandle(HttpServletReqeust,request,HttpServletResponse response,Object handler) throws Exception{
        System.out.println("AuthorizationInterceptor proHandle -- >");
        boolean flag = false;
        String servletPath = request.getServletPath();
        for(String s : IGNORE_URI){
            if(servletPath.contains(s)){
                flag = true;
                break;
            }
        }
        if(!flag){
            User user = (User) request.getSession().getAttribute("user");
            if(user == null){
                System.out.println("请求拦截");
                request.setAttribute("message","请先登录");
                request.getRequestDispatcher("loginForm").forward(request,response)
            }else {
                System.out.println("AuthorizationInterceptor放形请求");
                flag = true;
            }
        }
        return flag;
    }
}

  在springmvc-config.xml文件中配置拦截器

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path = "/*"/>
        <bean class = "org.fkit.interceptor.AuthorizationInterceptor"/>
    </mvc:interceptor>
</mvc>

  

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!