element-ui+springboot文件上传下载,获取后台header文件名

上传

前端

前端只能用form-meta的方式上传,这是硬伤

upload(param){
       var file = param.file;
       // new 出FormData
       var form = new FormData();
       // 添加文件
       form.append("file", file);
       form.append("storagePath",);
       form.append("pfolderName", );
       this.upload(form).then(res => {
       })

后台

@ApiOperation(value = "文件上传", notes = "文件上传")
	@PostMapping("/fileUpload")
	public R fileUpload(@RequestParam("file") MultipartFile file, @ApiParam(value="存储路径") String storagePath, @ApiParam(value="父文件夹名称") String pfolderName, @ApiParam(value="备注") String remarks, @ApiParam(value="文件夹id") Integer folderId) {
		return sourceMaterialService.fileUpload(sysReqDto,file,storagePath,pfolderName,remarks,folderId);
	}
public R fileUpload(MultipartFile file
			, String storagePath
			, String pfolderName
			, String remarks
			, Integer folderId) {

		log.info("文件上传folderId:{},路径:{}",sysReqDto.getTenantId(),sysReqDto.getAppId(),folderId,storagePath);
		Long fileSize = file.getSize();
		String fileName = file.getOriginalFilename();
		String realPath = fileUploadConfig.getRealPath() + "/" + storagePath;
		String url = realPath + "/" + fileName;
		//设置返回
		Map<String, String> resultMap = new HashMap<>(4);
		resultMap.put("fileName", fileName);
		resultMap.put("url", String.format(fileUploadConfig.getAccessPath() + "/%s", storagePath + "/" + fileName));
		resultMap.put("filePath", realPath);
		Integer count = baseMapper.queryFileCount(sysReqDto.getTenantId(), sysReqDto.getAppId(), storagePath, fileName, FileUtil.extName(file.getOriginalFilename()));
		if (count > 0) {
			return R.failed("该文件:"+fileName+",已存在");
		} else {
			try {
				File dest = new File(url);
				file.transferTo(dest);
				log.info("测试创建:{}",dest.exists());
				File isOk = new File(url);
				if (isOk.exists()){
					//成功
				}else {
					log.warn("文件:{}创建失败",fileName);
					return R.failed("创建文件失败:"+fileName);
				}
			} catch (Exception e) {
				log.error("上传文件异常:{}", e.getMessage());
				return R.failed("上传文件异常:"+fileName);
			}
		}
		log.info("上传文件:{}成功",fileName);
		return R.ok(resultMap);
	}

下载

前端

// 数据流必须用Blob取出

download(param).then((res) => {
	 const link = document.createElement('a')
	 let blob = new Blob([res.data],{type: 'application/vnd.ms-excel'});
	 //获取heads中的filename文件名
	 let temp = res.headers["content-disposition"].split(";")[1].split("filename=")[1];
	 link.style.display = 'none'
	 link.href = URL.createObjectURL(blob);
	 link.setAttribute('download', fileName)
	 document.body.appendChild(link)
	 link.click()
	 document.body.removeChild(link)
}).catch(error => {
 	console.log(error)
})

后台

@ApiOperation(value = "批量文件下载", notes = "批量文件下载")
	@PostMapping("download")
	public void download(,@RequestBody List<Integer> ids, HttpServletResponse response){
		sourceMaterialService.download( ids,response);
	}
public void download(List<Integer> ids, HttpServletResponse response) {
		log.info("批量下载文件ids:{}",sysReqDto.getTenantId(),sysReqDto.getAppId(), Arrays.asList(ids));
		List<SourceMaterial> infoByIds = baseMapper.getInfoByIds//获取下载信息
		log.info("开始下载文件,数量:{}",infoByIds.size());
		String realPath = fileUploadConfig.getRealPath();
		String zipName = "SM-"+LocalTime.now().toSecondOfDay()+".zip";
		response.setContentType("application/zip");
		response.setHeader("Content-Disposition", "attachment; filename="+zipName);
		ZipOutputStream zos = null;
		try {
			zos = new ZipOutputStream(response.getOutputStream());
			// 文件打包
			for (SourceMaterial sm : infoByIds){
				String filePath = realPath +"/" + sm.getStoragePath() + "/" + sm.getFileName();
				File file = new File(filePath);
				if (file.exists()){
					log.info("准备文件:{}", file.getName());
					FileInputStream in=new FileInputStream(file);
					zos.putNextEntry(new ZipEntry(file.getName()));
					byte[] buf = new byte[1024 * 1024];
					int len;
					while ((len = in.read(buf)) != -1) {
						zos.write(buf, 0, len);
					}
					in.close();
				}
			}
		} catch (IOException e) {
			log.error("批量文件下载失败:{}",e.getMessage());
			return;
		}finally {
			if (zos != null){
				try {
					zos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		log.info("下载文件结束");
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值