javaweb項目中的文件上傳下載功能的實現


框架是基於spring+myBatis的。

 

前台頁面的部分代碼:

<form action="${ctx}/file/upLoadFile.do"method="post" enctype="multipart/form-data" id="form"><table><tbody ><tr ><td>上傳文件:</td><td style="padding-left: 10px;"><input type="file" name="file" id="fileInput"></td><td style="padding-left: 80px;"><button type="submit" class="btn btn-primary btn-q btn-outline fa fa-upload"
           class="easyui-validatebox" data-options="required:true">上傳</button></td></tr><tr><td colspan="2"><span style="color:red">*上傳文件格式為xls,xlsx,txt,csv文件!</span>&nbsp;&nbsp;</td>
    </tr>
  </tbody>
</table></form>

 

{

 

  title : '操作',
  halign : 'center',
  align : 'center',
  width : 80,
  field : 'FILE_PATH',
  formatter: function(value,row,index){
  var path = "${ctx}/file/download.do?filePath=" + value ;
  var button = '<button type="button" class="btn btn-primary btn-q btn-outline fa fa-download" class="easyui-validatebox" 
           data-options="required:true">下載</button>';
          return "<a href='" + path  + "'>" + button +  "</a>";
}

上傳功能的方法:

@RequestMapping("/upLoadFile")
    public String upload(@RequestParam(value = "file", required = false) MultipartFile file, ModelMap model, HttpServletRequest request) 
        throws Exception {
          //設置相對路徑
        String realPath = request.getSession().getServletContext().getRealPath("/upload");
          //獲取文件的格式
        String extention = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
          //對格式進行篩選
        if(extention.equalsIgnoreCase("xls") || extention.equalsIgnoreCase("xlsx") || extention.equalsIgnoreCase("txt") 
        || extention.equalsIgnoreCase("csv")) {
          //在路徑下創建文件夾
        File f = new File(realPath);
            String fileName = file.getOriginalFilename();
            String uploadPath = realPath + File.separator + fileName;
            if(!f.exists()) {
                f.mkdir();
            }
          //文件的傳輸
            file.transferTo(new File(uploadPath));
            Upload upload = new Upload();
            upload.setFileName(fileName);
            upload.setFileLength(String.valueOf(file.getSize()));
            upload.setFileOwner(super.getLoginUser(request).getLoginId());
            upload.setFilePath("/upload/" + fileName);
          //將文件的基本信息存到數據庫
            fileQueryService.saveFile(upload);
            request.setAttribute("info","文件上傳成功!");
        } else {
            request.setAttribute("info","文件類型不正確,請上傳格式為xls,xlsx,txt,csv文件!");
        }
        return "page/file/fileInteraction";
    }

 下載功能的方法:

 

@RequestMapping("/download")

 

    public String download(String filePath, HttpServletRequest request,
                           HttpServletResponse response) {
        try {
          //獲取文件名
            String fileName = filePath.substring(filePath.lastIndexOf("/")+1);
            System.out.println(filePath);
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
          //處理下載彈出框名字的編碼問題
            response.setHeader("Content-Disposition", "attachment;fileName="
                    + new String( fileName.getBytes("gb2312"), "ISO8859-1" ));
          //獲取文件的下載路徑
            String path = request.getSession().getServletContext().getRealPath(filePath);
            System.out.println(path);
          //利用輸入輸出流對文件進行下載
            InputStream inputStream = new FileInputStream(new File(path));
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
            // 這里主要關閉。
            os.close();
            inputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //  返回值要注意,要不然就出現下面這句錯誤!
        //java+getOutputStream() has already been called for this response
        return null;
    }

最終效果:


下載頁面:


文件的上傳和下載完整版demo下載:

https://dwz.cn/fgXtRtnu 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM