文件上传下载

环境配置

1、pom.xml中添加依赖

      <dependency>
          <groupId>commons-fileupload</groupId>
          <artifactId>commons-fileupload</artifactId>
          <version>1.4</version>
      </dependency>

2、配置xml配置文件

<!--    mvc文件管理器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--    设置默认编码格式-->
        <property name="defaultEncoding" value="UTF-8"/>
<!--        设置最大文件上传大小-->
        <property name="maxUploadSize" value="31457280"/>
<!--        每次向内存写入大小-->
        <property name="maxInMemorySize" value="40960"/>
    </bean>

文件上传 

//通过封装好的工具类MultipartFile实现文件上传
public void upload(MultipartFile filename) {
        //获取文件名称
        String name = filename.getOriginalFilename();
        //获取随机名称作为存储名称,在服务器不需要查看,为了避免名称重复覆盖问题。
        String uuid = UUID.randomUUID().toString();
        try {
            //保存文件到服务器磁盘
            filename.transferTo(Path.of("服务器路径"+uuid));
        } catch (IOException e) {
            e.printStackTrace();
        }
}

文件下载

public void downLoad(HttpServletResponse response){
    String path = "服务器文件路径";
    String name = "从数据库获取文件名";
    //设置数据类型为二进制
    response.setContentType("application/octet-stream");
    //避免乱码,将名称转换为UTF-8
    try {
        name = new String(name.getBytes(StandardCharsets.UTF_8),"ISO8859-1");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    //避免浏览器直接打开文件,将其类型设置为附件形式,文件名为+name
    response.addHeader("Content-Disposition","attachement;filename="+name);
    //创建输出流
    OutputStream out = null;
    try {
        //获取响应输出流
        out = response.getOutputStream();
        //将文件以二进制的形式写入流
        out.write(FileUtils.readFileToByteArray(new File(path)));
        //关闭流
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值