一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

SpringMVC实现上传下载文件代码方法

时间:2022-09-08 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下SpringMVC实现上传下载文件代码方法,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

一、SpringMVC专门提供了CommonsMultipartResolver组件用于文件上传:

(1)maxUploadSize 文件最大限制,单位是byte

(2)maxInMemorySize 低于这个大小的文件暂存内存中

(3)defaultEncoding 默认编码utf-8

必须在spring-mvc.xml文件


       
         
        
        
        
        
        
       

二、SpringMVC文件上传引入jar包

必须在配置Pom.xml文件


        
            commons-fileupload
            commons-fileupload
            1.3.1
        
 
        
            commons-io
            commons-io
            2.4
        
 
        

三、实现【单个文件】上传

(1)JSP页面必须放在WEB-INF下 upload1.jsp 必须添加enctype="multipart/form-data"


    

照片:

(2) 写控制类 UploadController.java

@Controller
public class UploadController {
 
    @RequestMapping("upload1")
    public String getUpload(@RequestParam("imagefile") MultipartFile imagefile,
            HttpServletRequest request) {
        // 获取上传的服务器路径
        String pathString = request.getSession().getServletContext().getRealPath("/upload/");
        // 获取文件
        String fileName = imagefile.getOriginalFilename();
        
        System.out.println(fileName);
 
        // 判断上传的路径是否存在
        File file = new File(pathString);
        if (!file.exists()) {
            file.mkdirs();
        }
 
        System.out.println("上传路径=" + pathString +"/"+ fileName);
        // 文件不存在
        File targetFile = new File(pathString +"/"+ fileName);
        if (!targetFile.exists()) {
            try {
                targetFile.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
 
        try {
            // 上传
            imagefile.transferTo(targetFile);
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
 
        //注意:/springmvc5/WEB-INF/jsp/http:/localhost:8888/springmvc5/upload/1.gif.jsp
        //返回文件,必须是重定向文件
        return "redirect:http://localhost:8888/springmvc5/upload/" + fileName;
 
    } }

(3)效果

选择图片路径:

单击上传:

四、实现【多个文件】上传

(1)JSP页面(必须放在WEB-INF下) upload2.jsp 必须添加enctype="multipart/form-data"


    

照片1:

照片2:


(2) 写控制类 UploadController.java

@RequestMapping("upload2")
    public String getUpload2(HttpServletRequest request) {
 
        // 多文件上传
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获得多个文件
        Map map = multipartRequest.getFileMap();
 
        // 获取上传的服务器路径
        String pathString = request.getSession().getServletContext().getRealPath("/upload/");
        // 判断上传的路径是否存在
        File file1 = new File(pathString);
        if (!file1.exists()) {
            file1.mkdirs();
        }
 
        // 获取文件
        List list = new ArrayList();
 
        // 遍历数据
        for (MultipartFile file : map.values()) {
            String fileName = file.getOriginalFilename();
            System.out.println("上传路径=" + pathString +"/"+ fileName);
            // 文件不存在
            File targetFile = new File(pathString  +"/"+ fileName);
            if (!targetFile.exists()) {
                try {
                    targetFile.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
 
            try {
                // 上传
                file.transferTo(targetFile);
 
                // 保存路径
                list.add("http://localhost:8888/springmvc5/upload/" + fileName);
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
 
        }
        // 保存每个上传的路径
        request.setAttribute("files", list);
        
        return "showUpload";   //跳转到showUpload.jsp页面哦!
 
    }

注意:return "showUpload";是具体显示的页面;必须配置视图解析器在spring-mvc.xml文件中


(3)JSP页面: showUpload.jsp

<% List list =(List) request.getAttribute("files"); for(String str:list){ %> <%} %>

(4)效果

单击上传:

查看上传到服务器的图片

五、下载图片

(1)JSP页面 login.jsp

下载图片

(2)控制类DownController

@Controller
public class DownController {
 
    @RequestMapping("/download")
    public String download(@RequestParam String fileName,
            HttpServletRequest request, HttpServletResponse response) {
 
        // 设置响应编码
        response.setContentType("text/html;charset=utf-8");
 
        // 设置请求编码
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
 
        // 字节流
        BufferedInputStream bis=null;
        BufferedOutputStream bos=null;
 
        // 获取服务器的路径
        String path = request.getSession().getServletContext().getRealPath("/upload/");
 
        // 下载的路径
        String downPath = path +"/"+ fileName;
 
        try {
            // 文件大小
            long fileSize = new File(downPath).length();
            
            //设置内容类型
            response.setContentType("application/x-msdownload");
            //设置头信息
            response.setHeader("Content-disposition", "attachment; filename="+new String(fileName.getBytes("utf-8"),"ISO8859-1"));
            response.setHeader("Content-Length",String.valueOf(fileSize));
            //字节流
            bis = new BufferedInputStream(new FileInputStream(downPath));
            bos= new BufferedOutputStream(response.getOutputStream());
            //字节数组
            byte[] by = new byte[2048];
            
            //
            int length=0;
            
            //读取
            while((length=bis.read(by,0,by.length))!=-1){
                //写入
                bos.write(by, 0, length);
                
            }
            
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally{
            //关闭连接
             if(bis!=null){
                 try {
                    bis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
             }
             if(bos!=null){
                 try {
                     bos.close();
                 } catch (IOException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                 }
             }
        }
 
        return null;
 
    }
}

(3)效果

保存或打开如下:

热门栏目