基于SpringMVC 实现的上传/下载的Demo

1. 前言

本文的目的是:使用一个简单的上传下载Demo案例,将整理的知识进行总结。其中配有源码/ 图片/ 案例等

2. 源码地址

源码地址

3. 实现效果

在这里插入图片描述

4. 核心原理

4.1 设备

  • 两台tomcat服务器,一台服务器作为文件服务器,一台服务器作为项目服务器

4.2 核心依赖介绍

  • 解析返回json对象的依赖
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.12.1</version>
    </dependency>
  • 远程服务器上传文件的依赖
    <dependency>
      <groupId>com.sun.jersey</groupId>
      <artifactId>jersey-client</artifactId>
      <version>1.19</version>
    </dependency>
  • 识别请求中 参数是file的依赖
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.8.0</version>
    </dependency>

4.3 核心代码介绍

    @RequestMapping(method = RequestMethod.POST, value = "/uploadFile")
    public Map<String, Object> uploadFile(MultipartFile file) throws IOException {
        HashMap<String, Object> hashMap = new HashMap<>();

        // 文件名称
        String originalFilename = file.getOriginalFilename();
        // 表示获取扩展名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 避免文件名称冲突 使用uuid
        String uuid = UUID.randomUUID() + "_" + Utils.getCurrentDate();
        String newFileName = uuid.concat(suffix);

        // 创建 sun公司提供的jersey包中的client对象
        Client client = Client.create();
        WebResource webResource = client.resource(SERVER_ADDR + newFileName);

        // 将文件存储到另一个服务器上去
        webResource.put(String.class, file.getBytes());

        // 上传成功后 返回对应的状态
        hashMap.put("code", "200");

        HashMap<String, String> data = new HashMap<>();
        data.put("path", SERVER_ADDR);
        data.put("filename", newFileName);
        data.put("type", file.getContentType());
        hashMap.put("data", data);
        return hashMap;
    }
  • 上述的代码核心之处还是利用依赖,进行远程文件上传
    @GetMapping(value = "/downloadFile")
    public void downloadFile(String filename, String fileType, HttpServletResponse resp) throws IOException {
        // 1. 设置响应头
        resp.setHeader("Content-Disposition", "attachment;filename=" + filename);
        // 2. 设置响应类型
        resp.setContentType(fileType);
        // 3. 获取一个文件的输入流
        InputStream inputStream = new URL(SERVER_ADDR + filename).openStream();
        // 4. 设置一个输出流
        ServletOutputStream outputStream = resp.getOutputStream();
        // 5. 向浏览器响应文件即可
        IOUtils.copy(inputStream, outputStream);
    }

5. 结束

其实上述的代码比较简单,而且注释中写的很明白了。所以就不多做解释了。如果觉得代码对您有帮助的话,可以直接看源码。 同时也是非常欢迎评论下进行留言以及交流。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值