spring boot 上传下载文件

本文介绍了在Spring Boot项目中如何配置文件上传和下载功能,分别讲解了在application-prod和application-local环境的配置方法,并详细阐述了上传和下载的具体实现过程,还提及了FileUtils类在操作文件中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

在application-prod中的配置

在application-local中的配置

上传

@PostMapping("uploadDemand/{id}")
    @ApiOperation("报价单上传文件")
    public String uploadDemand(@RequestParam("file") MultipartFile file,@PathVariable String id) {
        // 获取原始名字
        String fileName = file.getOriginalFilename();
        // 获取后缀名
         String suffixName = fileName.substring(fileName.lastIndexOf("."));

         Integer fileType = null;
         if (suffixName.toLowerCase().equals(".xls") || suffixName.toLowerCase().equals(".xlsx")){
             fileType = 0;
         }
         if (suffixName.toLowerCase().equals(".pdf")) {
             fileType = 1;
         }
        // 文件保存路径
        String filePath = uploadFilePath;
        // 文件重命名,防止重复
        String fileNamesPath = filePath + UUID.randomUUID() + fileName;
        // 文件对象
        File dest = new File(fileNamesPath);
        // 判断路径是否存在,如果不存在则创建
        if(!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            // 保存到服务器中
            file.transferTo(dest);
            return "上传成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

下载

    @GetMapping("/downloadTemplate")
    @ApiOperation("下载")
    public void downloadOfferDemandFile(HttpServletResponse response,@RequestParam(value="fileName") String fileName,@RequestParam(value="filePath") String filePath){
        StringBuilder filePathAddres = new StringBuilder(); // 文件下载地址
            filePathAddres.append(filePath);
       
        File file = new File(filePathAddres.toString());
        try {
            FileUtils.downloadFile(file,fileName,response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

FileUtils类

/**
	 * 文件下载
	 *
	 * @param file
	 *            创建的文件对象 new File()
	 * @param response
	 *            HttpServletResponse响应
	 * @param fileName
	 *            指定下载文件的名称
	 * @throws IOException
	 *             当文件不存在或者创建文件流时 会抛此异常
	 */
	public static void downloadFile(File file, String fileName, HttpServletResponse response) throws IOException {
		if (!file.exists()) {
			throw new FileNotFoundException("file not found:" + file.getAbsolutePath());
		}
		BufferedInputStream bufferStream = new BufferedInputStream(new FileInputStream(file));
		byte[] buffer = new byte[1024];
		int n;
		if (fileName != null) {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition",  "attachment;filename="+ URLEncoder.encode(fileName, "utf-8"));
//			response.setHeader("Content-disposition",
//					"attachment; filename=" + new String(fileName.getBytes("gb2312"), "iso-8859-1"));
		}
		while (-1 != (n = bufferStream.read(buffer))) {
			response.getOutputStream().write(buffer, 0, n);
		}
		response.getOutputStream().flush();
		bufferStream.close();
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值