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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章