springmvc上传和下载文件

Spring MVC上传文件和下载文件

上传文件

1首先在jsp页面中创建一个form表单

  <form method="post" action="/hello.form" enctype="multipart/form-data">
      <input type="file" name="file">
      <input type="file" name="file">
    <button>提交</button>
    <a href="down.form?fileName=3.jpg">手机图片</a>
  </form>

2在springmvc.xml中注入配置

<bean id="CommonsMultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!--编码格式-->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!--上传文件大小-->
        <property name="maxUploadSize" value="10000000"></property>
    </bean>

3在控制层方面

  @RequestMapping("/hello.form")
    public String upload(MultipartFile file[],HttpServletRequest request) throws IOException {
         //循环上传路径
        for (int i = 0; i < file.length; i++) {
            String realPath = request.getServletContext().getRealPath("/down/");
            //获取上传的文件名
            String name = file[i].getOriginalFilename();
            //更改名字 为了防止名字重复而覆盖
            String name1=  new Random().nextInt(100)+name;
            File file1 = new File(realPath + name1);
            //transferTo()方法是springmvc封装的方法,用于图片上传时,把内存中图片写入磁盘
            file[i].transferTo(file1);
        }
        return "success";
    }

4打开jsp页面选取文件
在这里插入图片描述上传成功
在这里插入图片描述

下载文件中有些文件可以直接用超链接进行下载,但有些文件就不能,因此为了一劳永逸,我们统一进行转换格式

 @RequestMapping("/down.form")
    public ResponseEntity<byte[]> load(@RequestParam("fileName") String fileName,HttpServletRequest request) throws IOException {
        //首先获取下载的路径
        String realPath = request.getServletContext().getRealPath("/down/");
        File file = new File(realPath + fileName);
        //转换格式 某些进制的格式无法进行下载
        String name = new String(fileName.getBytes("UTF-8"), "iso-8859-1");

        //转流   获取Http的所有头部
        HttpHeaders hh = new HttpHeaders();
        hh.setContentDispositionFormData("attachment",name);

        hh.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),hh, HttpStatus.CREATED);

    }

之后我们就可以成功的下载文件了

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值