1. 程式人生 > 實用技巧 >Spring WebFlux(二)

Spring WebFlux(二)

1. 檔案上傳

  關鍵程式碼:

     public void save(File cenclosure,Collectfile collectfile) {
        try {
            InputStream inputStream = new FileInputStream(cenclosure);
            collectfile.setCenclosure(inputStream);
            String name = cenclosure.getName();
            collectfile.setCmenclosure(name);
        } 
catch (Exception e) { // TODO: handle exception e.printStackTrace(); } if (Validation.hasErrors()) { this.printError(Validation.getErrorsAsString()); return; } collectfileService.save(collectfile); }

  注意事項:

  1.其中引數cenclosure 要和前端form表單中的引數名稱一致,否則無法上傳

  2.將File型別轉換成流的形式,資料庫中以二進位制的形式儲存

2. 檔案下載

  關鍵程式碼:

/**
     * 檔案下載
     * @param omenclosure  檔名
     * @throws IOException 
     */
    public void downloadLocal(String id){
        try {
            //根據編號查詢得到實體類物件
            Collectfile collectfile = (Collectfile) collectfileService.findById(id);
            
            HttpServletResponse response 
= response(); //獲取InputStrem流 InputStream in = collectfile.getCenclosure(); response.setContentType("application/x-msdownload"); response.addHeader("Content-Disposition", "attachment; filename="+new String(collectfile.getCmenclosure().getBytes("gb2312"),"iso-8859-1")); OutputStream out =response.getOutputStream(); byte[] b = new byte[1024]; int l; while((l = in.read(b)) != -1){ out.write(b, 0, l); } in.close(); out.flush(); out.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }