SpringMVC处理文件上传下载

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/broccoli2/article/details/79771183

springmvc处理文件上传,可以将文件存储路径持久化数据库。代码很简单!!
废话少说,看代码!!

文件上传表单:

<form action="con/upload.do" method="post" enctype="multipart/form-data">  
     <input type="file" name="file" />  
     <input  type="submit" value="保存"/>  
</form>  

后台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("/static/uploadfile/");
            //上传文件名
            String filename = file.getOriginalFilename();
            //String fileType = originalFileName.substring(originalFileName.indexOf(".") + 1);//截取文件拓展名.jpg
            String persistFileUrl = "static/uploadfile/"+filename;//持久化路径
            File filepath = new File(path,filename);
            //判断路径是否存在,如果不存在就创建一个
            if (!filepath.getParentFile().exists()) { 
                filepath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文件当中
            file.transferTo(new File(path + File.separator + filename));

            Contact con = new Contact();
            con.setCONTACT_ID(45);
            con.setIMG(persistFileUrl);//将文件存储路径持久化数据库
            contactService.addOrUpdateImg(con);
            return "redirect:list.do";
        } else {
            return "error";
        }

     }

文件下载页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件下载</title>
</head>
<body>
<h3>文件下载</h3>
<a href="download?filename=${requestScope.user.image.originalFilename}">
   ${requestScope.user.image.originalFilename }
</a>
</body>
</html>

后台Controller:

/**
      * 文件下载
      * @param request
      * @param filename
      * @param model
      * @return
      * @throws Exception
      */
     @RequestMapping(value="/download")
     public ResponseEntity<byte[]> download(HttpServletRequest request,
             @RequestParam("filename") String filename,
             Model model)throws Exception {
        //下载文件路径
        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");
        //通知浏览器以attachment(下载方式)打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName); 
        //application/octet-stream : 二进制流数据(最常见的文件下载)。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
                headers, HttpStatus.CREATED);  
     }

源码下载

猜你喜欢

转载自blog.csdn.net/broccoli2/article/details/79771183