1. 程式人生 > >springboot專案實現檔案的上傳顯示和下載

springboot專案實現檔案的上傳顯示和下載

檔案上傳:

HTML上傳頁面程式碼:

<input type="file" class="form-control" name="file">

submit提交到controller,controller中的程式碼:

@RequestMapping(value = "/usershare", method = RequestMethod.POST)
    public String share(Model model, HttpServletRequest request,@RequestParam("file") MultipartFile file) {
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("sessusername");
        System.out.println("使用者名稱:"+username);
        String title = request.getParameter("title");
        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();
//        String filePath = request.getSession().getServletContext().getRealPath("fileupload/");
        String filePath = "D:\\fileupload\\";//固定儲存路徑
        File fileP = new File(filePath);
        try {
            userService.share(username, title, file.getBytes(), filePath, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/share/share.html";
    }

DAO中的具體儲存程式碼:

public void share(String username, String title, byte[] file, String filePath, String fileName) {
        //判斷上傳檔案的儲存目錄是否存在
        File targetFile = new File(filePath);
        if(!targetFile.exists() && !targetFile.isDirectory()){
            System.out.println(filePath+"  目錄不存在,需要建立");
            //建立目錄
            targetFile.mkdirs();
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath+fileName);
            out.write(file);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

這樣就將檔案通過檔案流寫入到了本地資料夾中。

顯示檔案和下載:

將檔名字從資料庫中取出來呈現到前臺頁面上,然後點選下載時傳遞檔名,通過檔名找到在固定目錄中的檔案,然後通過檔案流下載。

前端顯示程式碼:

<div th:if="${not #lists.isEmpty(list)}">
                    <table>
                        <tr>
                            <td width="115" height="37">標題</td>
                            <td width="115" height="37">內容</td>
                            <td width="132">發表時間</td>
                            <td width="180">發表使用者</td>
                            <td width="100">操作</td>
                        </tr>
                        <tr th:each="diary:${list}">
                            <td th:text="${diary.title}"></td>
                            <td th:text="${diary.fileName}"></td>
                            <td th:text="${diary.writeTime}"></td>
                            <td th:text="${diary.username}"></td>
                            <td><button class="btn btn-small btn-link" type="button" th:onclick="'javascript:download(\''+${diary.fileName}+'\')'">下載</button></td>
                        </tr>
                    </table>
                </div>

點選下載後通過JS函式傳遞到controller中,具體傳遞過程在這篇部落格中。

controller程式碼:

@RequestMapping(value = "/download", method = RequestMethod.POST)
    public void download(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //得到要下載的檔名
        String fileName = URLDecoder.decode(request.getParameter("diarycontent"),"utf-8");
        //fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8");
        //上傳的檔案都是儲存在D:\fileupload\目錄下的子目錄當中
        String fileSaveRootPath="D:\\fileupload\\";
        System.out.println(URLDecoder.decode(request.getParameter("diarycontent"),"utf-8"));
        //通過檔名找出檔案的所在目錄
        //String path = findFileSavePathByFileName(fileName,fileSaveRootPath);
        //String path = fileSaveRootPath;
        //得到要下載的檔案
        File file = new File(fileSaveRootPath + "\\" + fileName);
        //如果檔案不存在
        if(!file.exists()){
            request.setAttribute("message", "您要下載的資源已被刪除!!");
        }
        //處理檔名
        String realname = fileName.substring(fileName.indexOf("_")+1);
        //設定響應頭,控制瀏覽器下載該檔案
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));
        //讀取要下載的檔案,儲存到檔案輸入流
        FileInputStream in = new FileInputStream(fileSaveRootPath + "\\" + fileName);
        //建立輸出流
        OutputStream out = response.getOutputStream();
        //建立緩衝區
        byte buffer[] = new byte[1024];
        int len = 0;
        //迴圈將輸入流中的內容讀取到緩衝區當中
        while((len=in.read(buffer))>0){
            //輸出緩衝區的內容到瀏覽器,實現檔案下載
            out.write(buffer, 0, len);
        }
        //關閉檔案輸入流
        in.close();
        //關閉輸出流
        out.close();
    }
完成。