JAVA开发上传下载本地文件DEMO

 @RequestMapping(value = "/load",method = RequestMethod.POST)
    public void upload(HttpServletRequest req,HttpServletResponse res,@RequestParam("file") MultipartFile file){
        if(file.isEmpty()){
            throw new ToUserException("上传文件为空!");
        }
        Long time  = System.currentTimeMillis();
        try {
            String orginateFileName = new String(file.getOriginalFilename().getBytes("ISO-8859-1"),"UTF-8");
            System.out.println("导入原始文件名:"+orginateFileName);
            System.out.println("导入原始文件大小:"+file.getSize());
            String fileName = time+"_"+orginateFileName;
            File localFile = new File("D://"+fileName);
            file.transferTo(localFile);
            ServletUtils.toJson(fileName,req,res);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @GetMapping("/downLoad")
    public void download(String id, HttpServletRequest request, HttpServletResponse response) {
        System.out.println(id);
        try (
                FileInputStream inputStream = new FileInputStream(new File("D://"+id));
                ServletOutputStream outputStream = response.getOutputStream();
        ) {
            // 声明响应类型
            response.setContentType("application/x-download");
            // 下载的文件名称
            response.addHeader("Content-Disposition", "attachment;filename="+id);
            IOUtils.copy(inputStream, outputStream);
            //ServletUtils.toJson(request,response);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

直接贴的代码,有问题可以留言,demo版比较简单!
遇到问题1:请求报400 问题排查

  1. 需要消息头 Content-Type 设置为 multipart/form-data;
  2. spring需要配置文件解析器 配置如下 <!-- 定义文件上传解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设定默认编码 --> <property name="defaultEncoding" value="UTF-8" /> <!-- 设定文件上传的最大值5MB,5*1024*1024 --> <property name="maxUploadSize" value="5242880" /> <property name="maxInMemorySize" value="4096" /> </bean>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值