SpringMVC實現檔案上傳&下載(2)

Evan1024發表於2024-03-08

檔案上傳步驟

第一步:由於SpringMVC使用的是commons-fileupload實現,故將其元件引入專案中,這裡用到的是commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar。

第二步:spring-mvx中配置MultipartResolver處理器。可在此加入對上傳檔案的屬性限制。

第三步:在Controller的方法中新增MultipartFile引數。該引數用於接收表單中file元件的內容

第四步:編寫前臺表單。注意enctype="multipart/form-data"以及<input type="file" name="****"/>,如果是單個檔案直接使用MultipartFile 即可

springmvc.xml
<!-- 檔案上傳 -->
 <bean id="multipartResolver"  
   class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   <!-- 設定上傳檔案的最大尺寸為10MB -->  
   <property name="maxUploadSize">  
       <value>10000000</value>  
   </property>  
  </bean>  
controller

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class FileUploadController {


    //TODO:上傳程式碼
    @RequestMapping("/fileupload")
    public ModelAndView upload(String name,
            //上傳多個檔案
            @RequestParam("file") MultipartFile[] file,
            HttpServletRequest request) throws IllegalStateException,
            IOException {

        //獲取檔案 儲存位置
        String realPath = request.getSession().getServletContext()
                .getRealPath("/uploadFile");

        File pathFile = new File(realPath);

        if (!pathFile.exists()) {
            //資料夾不存 建立檔案
            pathFile.mkdirs();
        }
        for (MultipartFile f : file) {

            System.out.println("檔案型別:"+f.getContentType());
            System.out.println("檔名稱:"+f.getOriginalFilename());
            System.out.println("檔案大小:"+f.getSize());
            System.out.println(".................................................");
            //將檔案copy上傳到伺服器
            f.transferTo(new File(realPath + "/" + f.getOriginalFilename()));
             //FileUtils.copy
        }
        //獲取modelandview物件
        ModelAndView view = new ModelAndView();
        view.setViewName("redirect:index.jsp");
        return view;
    }



    //TODO:下載程式碼
    @RequestMapping(value = "/filedownload")  
    public ModelAndView download(HttpServletRequest request,  
            HttpServletResponse response) throws Exception {  

//        String storeName = "Spring3.xAPI_zh.chm";  
        String storeName="檔案.txt";
        String contentType = "application/octet-stream";  
        FileUploadController.download(request, response, storeName, contentType);  
        return null;  
    }  

    //檔案下載 主要方法
    public static void download(HttpServletRequest request,  
            HttpServletResponse response, String storeName, String contentType
           ) throws Exception {  

        request.setCharacterEncoding("UTF-8");  
        BufferedInputStream bis = null;  
        BufferedOutputStream bos = null;  

        //獲取專案根目錄
        String ctxPath = request.getSession().getServletContext()  
                .getRealPath("");  

        //獲取下載檔案露肩
        String downLoadPath = ctxPath+"/uploadFile/"+ storeName;  

        //獲取檔案的長度
        long fileLength = new File(downLoadPath).length();  

        //設定檔案輸出型別
        response.setContentType("application/octet-stream");  
        response.setHeader("Content-disposition", "attachment; filename="  
                + new String(storeName.getBytes("utf-8"), "ISO8859-1")); 
        //設定輸出長度
        response.setHeader("Content-Length", String.valueOf(fileLength));  
        //獲取輸入流
        bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
        //輸出流
        bos = new BufferedOutputStream(response.getOutputStream());  
        byte[] buff = new byte[2048];  
        int bytesRead;  
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
            bos.write(buff, 0, bytesRead);  
        }  
        //關閉流
        bis.close();  
        bos.close();  
    }  

}  

注意:注意:設定表單中form表單的屬性為:enctype="multipart/form-data"

相關文章