栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot附件上传和下载

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot附件上传和下载

附件上传
@PostResource(name = "新增填报", path = "/addEmmissionsReductionInput", requiredLogin = false, requiredPermission = false)
	@ApiOperation(value = "新增填报", response = Long.class)
	public ResponseData addEmmissionsReductionInput(
			 AddEmmissionsReductionInputParam params, MultipartFile file) {
		String result = emmissionsReductionInputService
				.addEmmissionsReductionInput(params,file);
		return ResponseData.success(result);
	}
@Transactional
	@Override
	public String addEmmissionsReductionInput(AddEmmissionsReductionInputParam params, MultipartFile file) {
		String enclosure = "";
		if(file!=null) {
			//文件存在的位置
			String path = tranPath;
			Date createTime = new Date();
			String dayTime = DateUtil.formatTime(createTime);
			File dir = new File(path+"/"+dayTime);
			if(!dir.isDirectory()) {
				dir.mkdirs();
			}
			//获取文件名
			String fileName = file.getOriginalFilename();
			File destFile = new File(dir.getAbsolutePath()+File.separator+fileName);
			//判断该文件下的上级文件夹是否存在 不存在创建
			if(!destFile.getParentFile().exists()) {
				destFile.getParentFile().mkdirs();
			}
			//上传文件
			try {
				file.transferTo(destFile);
			} catch (Exception e) {
				log.error("附件上传失败....");
				e.printStackTrace();
				return "附件上传失败";
			}//这一步结束就上传成功了。
			enclosure = destFile.getAbsolutePath();
		}
		EmmissionsReductionInputParam emmissionsReductionInputParam = modelMapper
				.map(params, EmmissionsReductionInputParam.class);
		emmissionsReductionInputParam.setEnclosure(enclosure);
		EmmissionsReductionInputParam searchParam = new EmmissionsReductionInputParam();
		searchParam.setYear(emmissionsReductionInputParam.getYear());
		searchParam.setQuarter(emmissionsReductionInputParam.getQuarter());
		searchParam.setCompanyName(emmissionsReductionInputParam.getCompanyName());
		searchParam.setCompanyType(emmissionsReductionInputParam.getCompanyType());
		searchParam.setLegalRepresentative(emmissionsReductionInputParam.getLegalRepresentative());
		//先检验原来数据库已经存在的记录,防止多次上报
		List dataList =
				emmissionsReductionInputMapper.getEmmissionsReductionInputList(searchParam);
		if(dataList!=null&&dataList.size()>0) {
			return "此公司在该季度已经上报,请勿重复上报";
		}
		Long count = emmissionsReductionInputMapper.insertEmmissionsReductionInput(emmissionsReductionInputParam);
		return "本次插入"+count+"条记录";
	}

主要实现将参数和附件一起上传,然后将上传附件的存放路径保存在对应的对象里,然后将对象入库保存。

附件下载
@GetResource(name = "附件下载", path = "/downloadEnclosure", requiredLogin = false, requiredPermission = false)
	@ApiOperation(value = "附件下载")
	public void downloadEnclosure(
			@RequestParam("filePath") String filePath,
			HttpServletResponse response
			) {
		Map params = new HashMap();
		params.put("filePath", filePath);
		emmissionsReductionInputService
				.downloadEnclosure(params,response);
	}
@Override
	public void downloadEnclosure(Map params, HttpServletResponse response) {
		String filePath = (String) params.get("filePath");
		File file = new File(filePath);
		if (file.exists()){//判断文件是否存在
			String fileName = file.getName();
			try {
				fileName = URLEncoder.encode(fileName, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				log.error("文件名编码失败"+e.toString());
			}//encode编码UTF-8 解决大多数中文乱码
            fileName = fileName.replace("+", "%20");//encode后替换空格  解决空格问题
            response.setContentType("application/force-download");//设置强制下载
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);//设置文件名
            byte[] buff = new byte[1024];// 用来存储每次读取到的字节数组
            //创建输入流(读文件)输出流(写文件)
            BufferedInputStream bis = null;
            OutputStream os = null;
            try {
                os = response.getOutputStream();
                bis = new BufferedInputStream(new FileInputStream(file));
                int i = bis.read(buff);
                while (i != -1) {
                    os.write(buff, 0, buff.length);
                    os.flush();
                    i = bis.read(buff);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (os != null){
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }else {
            log.info("文件不存在.......");
        }
		
	}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/275293.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号