rest方式处理文件服务

文件上传

创建FileInfo返回对象

在这里插入图片描述

public class FileInfo implements Serializable {

    private String path;

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

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }
}

创建文件上传controller

在这里插入图片描述

@RestController
@RequestMapping("/file")
public class FileController  {

    @PostMapping
    public FileInfo upload(MultipartFile file) throws IOException {

        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getSize());

        String folder = "D:\\workspace\\whale-security\\whale-security-demo\\src\\main\\java\\com\\whale\\web\\controller";
        File localFile = new File(folder,new Date().getTime()+".txt");

        //file.getInputStream()  也可以获取到文件流用阿里so上传

        file.transferTo(localFile);//写到本地文件

        return  new FileInfo(localFile.getAbsolutePath());
    }
}

测试

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

运行控制台打印:

在这里插入图片描述
在这里插入图片描述

下载

加入处理流的依赖

		<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version></version>
        </dependency>

下载方法 get请求

在这里插入图片描述

  @GetMapping("{id}")
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response){
        //jdk1.7语法 将流声明在try() 可以自动关闭
        try(
            InputStream inputStream = new FileInputStream(new File(folder,id+".txt"));
            OutputStream outputStream = response.getOutputStream();
            ) {
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition","attachment;filename=test.txt");//下载文件名称

            IOUtils.copy(inputStream,outputStream);//输入流copy到输出流

            outputStream.flush();


        }catch (Exception e){
            e.printStackTrace();
        }
    }

测试

访问 http://127.0.0.1:8080/file/1549983068479
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值