1. 程式人生 > >Spring Boot 檔案上傳與下載

Spring Boot 檔案上傳與下載

一、上傳檔案

	@RequestMapping(value="/upfile", method = RequestMethod.POST)
	public ResultVo uploadFile(@RequestParam MultipartFile file,HttpServletRequest request) throws Exception{
		if(file==null)
			return ResultVo.error("1", "上傳檔案不能為空");
		String fileName = file.getOriginalFilename();
		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {  
			return ResultVo.error("1", "上傳檔案格式錯誤,請上傳字尾為.xls或.xlsx的檔案");
	    } 
		
	    String filePath = request.getSession().getServletContext().getRealPath("upload/");
	    String path = filePath+fileName;
        try {
			File targetFile = new File(filePath);
			if(!targetFile.exists()){    
			    targetFile.mkdirs();    
			}
			BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(path));
			out.write(file.getBytes());
			out.flush();
			out.close();
        } catch (Exception e) {
            e.printStackTrace();
            ResultVo.error("1", "上傳失敗");
        }
        return ResultVo.success();
	}

二、下載檔案

	@RequestMapping(value = "/downtemp", method = RequestMethod.GET)
	public void downloadTemp(HttpServletRequest request,HttpServletResponse response) {
		String fileNames ="匯入模板.xls";
		logger.debug("下載模板檔名稱:"+fileNames);
		try {
			InputStream fis = FileController.class.getResourceAsStream("/templates/匯入模板.xls");
byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); response.reset(); response.setContentType("bin"); String agent = request.getHeader("USER-AGENT"); String codedfilename = ""; if (null != agent && -1 != agent.indexOf("MSIE") || null != agent && -1 != agent.indexOf("Trident")) {// ie String name = java.net.URLEncoder.encode(fileNames, "UTF8"); codedfilename = name; } else if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐,chrome等 codedfilename = new String(fileNames.getBytes("UTF-8"), "iso-8859-1"); } response.addHeader("Content-Disposition", "attachment; filename=\"" + codedfilename + "\""); response.getOutputStream().write(buffer); } catch (IOException e) { e.printStackTrace(); logger.error("下載模板檔案報錯"+e.getMessage(), e); } }
模板檔案存放位置:/src/main/resources/templates/匯入模板.xls