Java如何实现文件上传和下载

文件上传:

注:可以将保存的路径放在配置文件中,使用@Value注解注入;或者写进configuration类中,通过set/get方法获取配置文件中的属性值(这里就不演示了)

//文件的上传
public String upload(MultipartFile file) {

    //save.path: E:/test/       写在配置文件中
    
    @Value("${savePath}")
    private String savePath;
    File newFile = new File(savePath);
    try {
        file.transferTo(newFile);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "ok";
}

文件下载:从服务器上获取,你可以将需要下载的文件放在src/resources下

    @ApiOperation("模板下载")
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void TemplateDownload(HttpServletResponse response) {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("static/测试.xls");
			outputStream = response.getOutputStream();
            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("测试.xls").getBytes("gb2312"), "iso8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        } catch (IOException e) {
            log.error("下载异常:", e);
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
				if (outputStream != null) {
					outputStream.close();
				}
			} catch (IOException e) {
				log.error("下载异常:", e);
			}
		}
    }

文件下载:从自己电脑的磁盘的某个位置下载文件

    @ApiOperation("文件下载")
    @RequestMapping(value = "/discExport", method = RequestMethod.GET)
    public void discExport(HttpServletResponse response) {
       
        //获取路径
        String fileName = "test.txt";
		String exportPath = "E:/test/";
		InputStream inputStream = null;
		OutputStream outputStream = null;
        try {
            //File.separator 保证了在任何系统下不会出错。作用相当于 /
			inputStream = new FileInputStream(exportPath + File.separator + fileName);
			outputStream = response.getOutputStream();
            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName).getBytes("gb2312"), "iso8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        } catch (IOException e) {
            log.error("下载异常:", e);
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
				if (outputStream != null) {
					outputStream.close();
				}
			} catch (IOException e) {
				log.error("下载异常:", e);
			}
		}
    }

转载请注明!!!谢谢

 

 

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值