springmvc文件的上传和下载

简介: springmvc文件的上传和下载

Spring MVC为文件上传提供了直接的支持,这种支持是用即插即用的MultipartResolver实现的。Spring MVC使用Apache Commons FileUpload技术实现了一个MultipartResolver实现类:CommonsMultipartResolver。因此,SpringMVC的文件上传还需要依赖Apache Commons FileUpload的组件。


20180506173242366.png

1.前台通过ajax获取到服务器返回的json的文件的信息展示到页面。

2018050617171759.png

ajax展示文件代码

  <script type="text/javascript">
  //动态加载文件
  $(function() {
    $.ajax({
        type: 'post',
        url: 'findfile',
        contentType: 'application/json;charset=utf-8',
        success: function (data) { //返回json结果
          var ol = $("#fileol");
          var filedown = $("#filedown");
          filedown.empty();
          ol.empty();
        $.each(data,function(index,val){
          ol.append("<li>"+val.fileName+"</li>");
          filedown.append('<a href=download/'+val.fileId+'><span class="glyphicon glyphicon-save" aria-hidden="true"></span></a> <br>');        
        });
        }
    });
  });
  </script>

通过页面的id元素来获取控件,然后把取得的数据填充进去。

提交表单时需要选择文件的类型

from表单添加属性

enctype="multipart/form-data"

springmvc.xml配置上传解析器

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设定默认编码 -->
        <property name="defaultEncoding" value="UTF-8" />
        <!-- 设定文件上传的最大值5MB,5*1024*1024 -->
        <property name="maxUploadSize" value="5242880" />
        <property name="maxInMemorySize" value="4096" />
    </bean>

后台上传文件的代码,使用MultipartFile类就可以获取文件的相关信息。

  //上传文件
  @RequestMapping("/uploadfile")
  public ModelAndView uploadfile(
      HttpServletRequest request,
      MultipartFile file//接收文件
      ) throws Exception {
    ModelAndView modelAndView = new ModelAndView();
    //原始名称
    String originalFilename = file.getOriginalFilename();
    //上传文件
    if(file!=null && originalFilename!=null && originalFilename.length()>0){
      Pan pan=new Pan();
      //存储的物理路径
      String fileurl = pan.getFileuploadurl();
      //文件的全路径
      File newFile = new File(fileurl+originalFilename);
      //将内存中的数据写入磁盘
      file.transferTo(newFile);
      //访问的路径
      String file_url=pan.getFiledownurl()+originalFilename;
      List<ZhangFile> zhangFileList=zhangFileService.selectAllZhangFile();
      int length=zhangFileList.size();
      //判断数据库里面是否有这个文件
      boolean flag=false;
      for(int i=0;i<length;i++){
        if(zhangFileList.get(i).getFileName().equals(originalFilename)){
          flag=true;
          break;
        }
      }
      //没有的话就插入
      if(!flag){
        ZhangFile zhangfile=new ZhangFile();
        zhangfile.setFileName(originalFilename);
        zhangfile.setFileUrl(file_url);
        zhangfile.setFileTime(new Date());
        zhangFileService.insert(zhangfile);
      }
      modelAndView.addObject("zhangfilelist", zhangFileList);
      /*System.out.println(zhangFileList.toString());
      System.out.println(originalFilename+" "+newFile);*/
    }
    //modelAndView.setViewName("admin/other/other-index");
    return new ModelAndView("redirect:/admin/other-index");
  }

下载文件的代码:

    // 下载功能
    @RequestMapping(value = "/download/{fileId}")
    public void download(HttpServletRequest request,
            HttpServletResponse response, @PathVariable("fileId") Integer fileId)
            throws Exception {
        // 前台传来id,根据id从数据库找到对应的文件名字
        ZhangFile zhangfile = zhangFileService.selectByPrimaryKey(fileId);
        String filename = zhangfile.getFileName();
        response.setContentType("text/html;charset=UTF-8");    
        request.setCharacterEncoding("UTF-8");  
        // 读取目标文件,通过response将目标文件写到客户端
        // 获取目标文件的绝对路径
        // 下载文件路径前缀 path="D:/OnlineJudge/tomcat_normal/webapps/StudyFiles/"
        String path = new Pan().getFileuploadurl();
        String fullFileName = path + filename;
        long fileLength = new File(fullFileName).length();    
        // 下载显示的文件名,解决中文名称乱码问题
        if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
            filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
        }// firefox浏览器
        else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
            filename = URLEncoder.encode(filename, "UTF-8");
        }// IE浏览器
        response.reset();
        // 设置文件MIME类型
        response.setContentType(request.getServletContext().getMimeType(
                filename));
        // 设置Content-Disposition
        response.setHeader("Content-Disposition", "attachment;filename="
                + filename);
        response.setHeader("Content-Length", String.valueOf(fullFileName));    
        // 读取目标文件,通过response将目标文件写到客户端
        // 读取文件
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fullFileName));    
        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());    
        byte[] buff = new byte[2048];    
        int bytesRead;    
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {    
            bos.write(buff, 0, bytesRead);    
        }    
        bis.close();    
        bos.close();    
    }

这样可以下载的文件在火狐和谷歌浏览器可以显示中文名字。

20180506172804195.png

但是IE浏览器就下载下来的名字和格式会乱了,需要自己用打开方式选择来打开,这是一个还没有解决的问题,先记录下来。

20180506213137322.png

相关文章
|
7月前
SpringMVC解决下载文件名乱码的问题
SpringMVC解决下载文件名乱码的问题
64 0
|
1月前
SpringMVC之文件上传和下载
【1月更文挑战第20天】SpringMVC之文件上传和下载
30 1
|
7月前
|
前端开发 Java 数据库连接
SpringMvc第四战-【SpringMvc文件上传,下载】
SpringMvc第四战-【SpringMvc文件上传,下载】
|
7月前
|
设计模式 前端开发 Java
SpringMvc文件上传下载一条龙服务教会你
SpringMvc文件上传下载一条龙服务教会你
69 0
|
7月前
|
前端开发 Java 数据库
SpringMVC之文件的上传下载(教你如何使用有关SpringMVC知识实现文件上传下载的超详细博客)
SpringMVC之文件的上传下载(教你如何使用有关SpringMVC知识实现文件上传下载的超详细博客)
69 0
|
5天前
|
前端开发 Java Maven
如何在Spring MVC中实现图片的上传和下载功能
如何在Spring MVC中实现图片的上传和下载功能
|
1月前
|
存储 前端开发 Java
SpringMVC 文件上传和下载
SpringMVC 文件上传和下载
16 0
|
6月前
|
SQL JavaScript Java
SpringMVC之文件上传下载以及jrebel的使用
SpringMVC之文件上传下载以及jrebel的使用
40 0
|
7月前
|
SQL 缓存 前端开发
SpringMVC之文件上传下载以及jrebel的使用
SpringMVC之文件上传下载以及jrebel的使用
45 0
|
7月前
|
存储 前端开发 JavaScript
SpringMVC之文件上传下载
SpringMVC之文件上传下载
109 0