天天看點

SpringMVC實作檔案的上傳下載下傳

SpringMVC檔案上傳下載下傳

      • 1. 步驟分析
      • 2. 代碼實作
      • 3. 運作測試

1. 步驟分析

  • 建立好工程并配置好SpringMVC基本環境,并引入上傳檔案需要的兩個包:commons-fileupload-1.3.1.jar和commons-io-2.4.jar。
  • 建立上傳頁面upload.jsp
  • 在Spring的核心配置檔案中注冊上傳處理器
  • 編寫Controller層,從頁面擷取到然後存入指定的檔案夾
  • 編寫下載下傳和顯示界面show.jsp
  • 實作controller層下載下傳功能

2. 代碼實作

2.1、導入jar包

<dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.8.0</version>
 </dependency>
 <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
 </dependency>
           

2.2、建立upload.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>圖檔上傳下載下傳</title>
    <style>
        #box{
            width: 600px;
            height: 600px;
            margin: 100px auto;
        }
    </style>
</head>
<body>
<div id="box">
    <form action="/springmvc/oss.do" method="post" enctype="multipart/form-data">
       選擇檔案:<input type="file" name="img"/><br/>
        <input type="submit" value="送出">
    </form>
</div>
</body>
</html>
           

2.3、在SpringMVC核心配置檔案注冊上傳處理器

<mvc:resources mapping="/upload/**" location="/upload/"></mvc:resources>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"/>
        <!-- 設定上傳檔案的大小上限,機關:byte,10m=1024k 1k=1024b -->
        <property name="maxUploadSize" value="10240000"/>
    </bean>
           

2.4、編寫Controller層

@RequestMapping("/upload.do")
    public ModelAndView upload(MultipartFile file, HttpServletRequest req) throws IOException {
        // 獲得原始檔案名稱
        String originalFileName = file.getOriginalFilename();
        String suffixName = originalFileName.substring(originalFileName.lastIndexOf("."));
        // 生成新檔案名
        String newFlieName = UUID.randomUUID().toString() +suffixName;
        // 儲存到指定的檔案路徑
        String uploadDir = req.getServletContext().getRealPath("/upload");
        File f = new File(uploadDir);
        if(!f.exists()){
            f.mkdir();
      	}
      	file.transferTo(new File(uploadDir,newFlieName));
        System.out.println("檔案上傳到伺服器的位置:" + uploadDir + "/" + newFlieName);
        ModelAndView mv = new ModelAndView();
        mv.addObject("newFlieName",newFlieName);
        mv.addObject("originalFileName",originalFileName);
        mv.setViewName("show");
        return mv;
    }
           

2.5、編寫下載下傳和顯示界面show.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>圖檔上傳下載下傳</title>
</head>
<body>
<div>${originalFileName}上傳成功!</div>
<img src="<%=request.getContextPath() %>/upload/${newFlieName}" style="width:300px; height: 200px;">
<a href="<%=request.getContextPath() %>/download.do?newImgName=${newFlieName}&originalFileName=${originalFileName}">下載下傳</a>
</body>
</html>
           

2.6、實作controller層下載下傳功能

@RequestMapping("/download.do")
    public ResponseEntity<byte[]> download(HttpServletRequest request,String newImgName,String originalFileName) throws IOException {
        // 擷取檔案所在檔案夾路徑
        String path = request.getServletContext().getRealPath("/upload/")+newImgName;
        // 讀取圖檔
        byte[] imgbody = FileUtils.readFileToByteArray(new File(path));
        // 防止下載下傳亂碼
        String downloadImgName = new String(originalFileName.getBytes("UTF-8"), "iso-8859-1");
        // 設定響應頭
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentDispositionFormData("attachment",downloadImgName);
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(imgbody, httpHeaders, HttpStatus.OK);
        return responseEntity;
 }
           

3. 運作測試

SpringMVC實作檔案的上傳下載下傳