1. 程式人生 > 其它 >201971010101-阿麗米拉 實驗二 個人專案—《{0-1}揹包問題》專案報告

201971010101-阿麗米拉 實驗二 個人專案—《{0-1}揹包問題》專案報告

導包

<dependencies>
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.3</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
</dependencies>

檔案上傳配置

spring-mvc.xml

<!--檔案上傳配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--請求得編碼個,必須和jsp得pageEncoding屬性一致,以便正確讀取表單的內容,預設 ISO-8859-1-->
    <property name="defaultEncoding" value="utf-8"/>
    <!--上傳檔案大小上限,單位為位元組(10485760=10M)-->
    <property name="maxUploadSize" value="10485760"/>
    <property name="maxInMemorySize" value="40960"/>
</bean>

上傳-前端

<form action="${pageContext.request.contextPath}/upload2" enctype="multipart/form-data" method="post">
  <input type="file" name="file">
  <input type="submit">
</form>

上傳-後端

@Controller
public class FileController {
    // @RequestParam("file") 將name=file控制元件得到的檔案封裝為CommonsMultipartResolver物件
    // 批量上傳CommonsMultipartResolver則為陣列即可
    @RequestMapping("/upload")
    public String upload(@RequestParam("file") CommonsMultipartFile file,
                         HttpServletRequest request) throws IOException {
        // 獲取檔名: file.getOriginalFilename();
        String uploadFileName = file.getOriginalFilename();

        // 如果檔名為空,直接返回到首頁!
        if ("".equals(uploadFileName)) {
            return "redirect:/index.jsp";
        }
        System.out.println("上傳檔名: " + uploadFileName);

        // 上傳路徑儲存設定
        String path = request.getServletContext().getRealPath("/upload");
        // 如果路徑不存在,建立一個
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        System.out.println("上傳檔案儲存地址: " + realPath);

        InputStream is = file.getInputStream();
        FileOutputStream os = new FileOutputStream(new File(realPath, uploadFileName));

        // 讀取寫出
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
            os.flush();
        }
        os.close();
        is.close();
        return "redirect:/index.jsp";
    }

    /*
     * 採用file.Tranto 來儲存上傳的檔案
     */
    @RequestMapping("/upload2")
    public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        // 上傳路徑儲存設定
        String path = request.getServletContext().getRealPath("/upload");
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        // 上傳檔案地址
        System.out.println("上傳檔案儲存地址: " + realPath);

        // 通過CommonsMultipartFile的方法直接寫檔案(注意這個時候)
        file.transferTo(new File(realPath + "/" + file.getOriginalFilename()));

        return "redirect:/index.jsp";
    }
}

檔案下載-後端

    @RequestMapping("/download")
    public String downloads(HttpServletResponse response, HttpServletRequest request) throws IOException {
        // 要下載的圖片地址
        String path = request.getServletContext().getRealPath("/upload");
        String fileName = "2019年公務員多省聯考《申論》題(天津卷).pdf";

        // 1.設定response 響應頭
        response.reset();//設定頁面不快取,清空buffer
        response.setCharacterEncoding("UTF-8");//字元編碼
        response.setContentType("multipart/form-data");//二進位制傳輸資料
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));

        // 2.讀取檔案
        File file = new File(path, fileName);
        FileInputStream input = new FileInputStream(file);

        // 3.寫出檔案
        ServletOutputStream out = response.getOutputStream();

        byte[] buff = new byte[1024];
        int index = 0;
        while ((index = input.read(buff)) != -1) {
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();
        return null;
    }