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


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值