SpringMVC上傳與下載

 

springMVC中的上傳操作

       上傳需要另外導入以下兩個jar包,可以在struts2裏找到。

         1.commons-fileupload-1.3.1.jar

2.commons-io-2.2.jar

 

在springMVC的xml中的代碼

      

<!-- 上傳文件配置 -->

      <bean name="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

         <property name="defaultEncoding" value="UTF-8"/>

      </bean>

 

Upload.java

@Controller

public class FileuploadController {

    @RequestMapping("/upload")

    public ModelAndView upload(HttpServletRequest req,@RequestParam("file") CommonsMultipartFile file) throws IOException {

       ModelAndView mv =new ModelAndView();

       //獲取上傳的目錄

       String path=req.getRealPath("/Files");

       //獲得文件的輸入流

       InputStream is=file.getInputStream();

       //輸出流寫入文件到上傳目錄

       OutputStream os=new FileOutputStream(new File(path,file.getOriginalFilename()));

       //上傳過程

       int len=0;

       byte[] buffer=new byte[400];

       while((len=is.read(buffer))!=-1) {

           os.write(buffer, 0, len);

       }

       //關閉資源

       os.close();

       is.close();

       mv.setViewName("hello");

       return mv;

    }

}

批量上傳與struts2中的寫法一樣,把file改爲數組就可以了。在上傳方法中@RequestParam("file")是必須要有的否則會報錯。

 

Jsp 頁面

<form action="upload.html" method="post" enctype="multipart/form-data">

         <input type="file" name="file"><br>

         <input type="submit" value="上傳">

      </form>

 

SpringMVC中的下載操作

 

下載操作與servlet裏面的下載一樣,這裏只寫controller裏的代碼

 

Download.java

@Controller

public class DownloadController {

  

   @RequestMapping("/download")

   public void download(HttpServletRequest req,HttpServletResponse resp,String fileName) throws IOException {

      //獲取文件所在路徑

      String path=req.getServletContext().getRealPath("/Files");

      //設置文件名的編碼格式,解決下載的中文文件名稱亂碼

      String downloadFileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");

      //輸入流讀取文件

      File file=new File(path,fileName);

      InputStream is=new FileInputStream(file);

      //將文件寫入客戶端硬盤

      OutputStream os=resp.getOutputStream();

     

      resp.setCharacterEncoding("UTF-8");

      resp.setHeader("Content-Disposition", "attachment;filename="+downloadFileName);

      //org.apache.commons.io包下的IOUtils,注意不要寫錯

      IOUtils.copy(is, os);

      //關閉輸入輸出流

      os.close();

      is.close();

   }

}

 

這種寫法實測可以解決下載不了中文文件名稱的文件,並且不會出現亂碼等問題。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章