SSM簡單實現文件上傳和下載


一、配置spring-mvc

    <!-- 配置多媒體文件解析器 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 設定默認編碼 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 設定文件上傳的最大值2MB, 2*1024*1024 -->
        <property name="maxUploadSize" value="2097152"></property>
        <!--resolveLazily屬性啟用是為了推遲文件解析,以便在UploadAction 中捕獲文件大小異常--> 
        <property name="resolveLazily" value="true"/>    
    </bean>

實現文件上傳和下載需要添加依賴

<!-- 文件上傳 -->  
<dependency>  
<groupId>commons-fileupload</groupId>  
<artifactId>commons-fileupload</artifactId>  
<version>1.3</version>  
</dependency>
<!-- 文件上傳 -->  
<dependency>  
<groupId>commons-io</groupId>  
<artifactId>commons-io</artifactId>  
<version>1.3.2</version>  
</dependency>

 

二、實現文件上傳

1、文件上傳Controller

    /**  
                   * 文件上傳功能  
      * @param file  
      * @return  
      * @throws IOException   
      */ 
    @RequestMapping(value="/upload",method=RequestMethod.POST)
    public @ResponseBody  ModelAndView upload(@RequestParam("file")MultipartFile file, HttpServletRequest request) throws IOException {
       ModelAndView mv = new ModelAndView("message");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
        String res = sdf.format(new Date());

        // uploads文件夾位置
        String rootPath = request.getSession().getServletContext().getRealPath("WEB-INF/upload");
        // 原始名稱
        String originalFileName = file.getOriginalFilename();
        // 新文件名
        String newFileName = "sliver" + res + originalFileName.substring(originalFileName.lastIndexOf("."));
        // 創建年月文件夾
        Calendar date = Calendar.getInstance();
        File dateDirs = new File(date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH)+1));

        // 新文件
        File newFile = new File(rootPath + File.separator + dateDirs + File.separator + newFileName);
        // 判斷目標文件所在目錄是否存在
        if( !newFile.getParentFile().exists()) {
            // 如果目標文件所在的目錄不存在,則創建父目錄
            newFile.getParentFile().mkdirs();
        }
        System.out.println(newFile);
        // 將內存中的數據寫入磁盤
        file.transferTo(newFile);
        // 完整的url
        
       String fileUrl = date.get(Calendar.YEAR) + "/" + (date.get(Calendar.MONTH)+1) + "/" + newFileName;
       mv.addObject("path", fileUrl);
       return  mv;
    }

2、fileupoad.jsp

<%@ 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=ISO-8859-1">  
<title>文件上傳下載</title>  
</head>  
<body>  
    <form action="user/upload.action" method="post" enctype="multipart/form-data">  
        選擇文件:<input type="file" name="file" width="120px">  
        <input type="submit" value="上傳">  
    </form>  
    <hr>  
    <form action="user/down.action" method="get">  
        <input type="submit" value="下載">  
    </form>  
</body>  
</html>

3、實現結果

 

 

 三、實現文件下載

1、下載的controller

     /**  
     * 文件下載功能  
     * @param request  
     * @param response  
     * @throws Exception  
     */  
    @RequestMapping("/down")  
    public void down(HttpServletRequest request,HttpServletResponse response) throws Exception{  
        //模擬文件,myfile.txt為需要下載的文件  
        String fileName = request.getSession().getServletContext().getRealPath("WEB-INF/upload/2020/1")+"/sliver20200115164910583.txt";  
        //獲取輸入流  
        InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));  
        //假如以中文名下載的話  
        String filename = "下載文件.txt";  
        //轉碼,免得文件名中文亂碼  
        filename = URLEncoder.encode(filename,"UTF-8");  
        //設置文件下載頭  
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);    
        //1.設置文件ContentType類型,這樣設置,會自動判斷下載文件類型    
        response.setContentType("multipart/form-data");   
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());  
        int len = 0;  
        while((len = bis.read()) != -1){  
            out.write(len);  
            out.flush();  
        }  
        out.close();  
    }  

 

 2、實現過程

 

 

每天學一點、日后往學習深點的實現過程。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM