spring mvc實現文件上傳與下載


文件上傳

在pom.xml中引入spring mvc以及commons-fileupload的相關jar

        <!-- spring mvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.13.RELEASE</version>
        </dependency>
        
        <!-- 文件上傳與下載 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>

在springmvc.xml中加入文件上傳的相關配置

   <bean id="multipartResolver"  
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <!-- 上傳文件大小上限,單位為字節(10MB) -->
        <property name="maxUploadSize">  
            <value>10485760</value>  
        </property>  
        <!-- 請求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內容,默認為ISO-8859-1 -->
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
    </bean>

在jsp文件中加入form表單

     <form action="upload" enctype="multipart/form-data" method="post">
        <table>
            <tr>
                <td>文件描述:</td>
                <td><input type="text" name="description"></td>
            </tr>
            <tr>
                <td>請選擇文件:</td>
                <td><input type="file" name="file"></td>
            </tr>
            <tr>
                <td><input type="submit" value="上傳"></td>
            </tr>
        </table>
    </form>

添加文件上傳的方法

//上傳文件會自動綁定到MultipartFile中
     @RequestMapping(value="/upload",method=RequestMethod.POST)
     public String upload(HttpServletRequest request,
            @RequestParam("description") String description,
            @RequestParam("file") MultipartFile file) throws Exception {

        //如果文件不為空,寫入上傳路徑
        if(!file.isEmpty()) {
            //上傳文件路徑
            String path = request.getServletContext().getRealPath("/file/");
            //上傳文件名
            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));
         request.setAttribute("uploadfileName", filename);
            return "success";
        } else {
            return "error";
        }

     }

  

文件下載

在頁面給一個超鏈接,其href屬性值就是要下載文件的文件名

SpringMVC提供了一個ResponseEntity類型,使用它可以很方便地定義返回的HttpHeaders和HttpStatus

<a href="download?filename=${uploadfileName}"> ${uploadfileName} </a>

 

     @RequestMapping(value="/download")
     public ResponseEntity<byte[]> download(HttpServletRequest request,
             @RequestParam("filename") String filename)throws Exception {
        //下載文件路徑
        String path = request.getServletContext().getRealPath("/file/");
        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);  
     }

  

 


免責聲明!

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



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