Spring Security技术栈开发企业级认证与授权(六)使用REST方式处理文件服务

Spring Boot实现文件的上传和下载十分便捷,之前已经写了一篇关于Spring Boot实现文件上传的博客,用的是浏览上传的,而本篇博客使用的是代码模拟上传,两种方式不一样,可以参考一下。

一、文件上传

通过RESTful API上传文件,代码如下:

package com.lemon.security.web.controller;

import cn.hutool.core.io.IoUtil;
import com.lemon.security.web.dto.FileInfo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author lemon
 * @date 2018/4/2 下午2:19
 */
@RestController
@RequestMapping("/file")
public class FileController {

    private static String folder = "/Users/lemon/IdeaProjects/spring-security/lemon-security-demo";

    @PostMapping
    public FileInfo upload(@RequestParam("file") MultipartFile file) throws IOException {
        System.out.println("上传文件的表单name值为:" + file.getName());
        System.out.println("文件路径为:" + file.getOriginalFilename());
        System.out.println("文件大小为:" + file.getSize());
        File localFile = new File(folder, System.currentTimeMillis() + ".txt");
        // 执行上传操作
        file.transferTo(localFile);
        return new FileInfo(localFile.getAbsolutePath());
    }
}

上面的代码的FileInfo类就是一个包含文件路径的一个JavaBean。

package com.lemon.security.web.dto;

import lombok.Data;

/**
 * @author lemon
 * @date 2018/4/2 下午2:24
 */
@Data
public class FileInfo {

    private String path;

    public FileInfo(String path) {
        this.path = path;
    }
}

测试文件上传的代码为:

@Test
public void fileUpload() throws Exception {
    String result = mockMvc.perform(MockMvcRequestBuilders.fileUpload("/file")
            .file(new MockMultipartFile("file", "test.txt", "multipart/form-data", "hello world".getBytes("UTF-8"))))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andReturn().getResponse().getContentAsString();
    System.out.println(result);
}

二、文件下载

文件下载的代码为:

package com.lemon.security.web.controller;

import cn.hutool.core.io.IoUtil;
import com.lemon.security.web.dto.FileInfo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author lemon
 * @date 2018/4/2 下午2:19
 */
@RestController
@RequestMapping("/file")
public class FileController {

    private static String folder = "/Users/lemon/IdeaProjects/spring-security/lemon-security-demo";

    @GetMapping("/{id}")
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) {
        System.out.println(folder);
        try (
                // 这是JDK7的特性,关于流的操作,可以写在try后面的圆括号里,这样就无需手动关闭流
                InputStream inputStream = new FileInputStream(new File(folder, id + ".txt"));
                OutputStream outputStream = response.getOutputStream()
        ) {
            // 设置下载的文件类型
            response.setContentType("application/x-download");
            // 设置下载后的文件名
            response.setHeader("Content-Disposition", "attachment;filename=test.txt");
            IoUtil.copy(inputStream, outputStream);
            // 刷新输出流
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

从浏览器访问http://localhost:8080/file/152445566433就可以将之前模拟上传的文件下载下来,其中链接后面的数字是文件的上传后的名称。

Spring Security技术栈开发企业级认证与授权系列文章列表:

Spring Security技术栈开发企业级认证与授权(一)环境搭建
Spring Security技术栈开发企业级认证与授权(二)使用Spring MVC开发RESTful API
Spring Security技术栈开发企业级认证与授权(三)表单校验以及自定义校验注解开发
Spring Security技术栈开发企业级认证与授权(四)RESTful API服务异常处理
Spring Security技术栈开发企业级认证与授权(五)使用Filter、Interceptor和AOP拦截REST服务
Spring Security技术栈开发企业级认证与授权(六)使用REST方式处理文件服务
Spring Security技术栈开发企业级认证与授权(七)使用Swagger自动生成API文档
Spring Security技术栈开发企业级认证与授权(八)Spring Security的基本运行原理与个性化登录实现
Spring Security技术栈开发企业级认证与授权(九)开发图形验证码接口
Spring Security技术栈开发企业级认证与授权(十)开发记住我功能

示例代码下载地址:

项目已经上传到码云,欢迎下载,内容所在文件夹为chapter006

猜你喜欢

转载自blog.csdn.net/lammonpeter/article/details/79787861