zoukankan      html  css  js  c++  java
  • springBoot中使用使用junit测试文件上传,以及文件下载接口编写

    本篇文章将介绍如何使junit在springBoot中测试文件的上传,首先先阅读如何在springBoot中进行接口测试.

    文件上传操作测试代码

    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.http.MediaType;
    import org.springframework.mock.web.MockMultipartFile;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
    import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
    import org.springframework.test.web.servlet.setup.MockMvcBuilders;
    import org.springframework.web.context.WebApplicationContext;
    
    import java.time.LocalDateTime;
    import java.time.ZoneId;
    import java.util.Date;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class BootStarterSecurityDemoApplicationTests {
    
      @Test
      public void contextLoads() {
      }
    
      @Autowired
      private WebApplicationContext wac;
    
      private MockMvc mockMvc;
    
      /**
       * 在每次测试执行前构建mvc环境
       */
      @Before
      public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
      }
      /**
       * 测试上传文件
       */
      @Test
      public void whenUploadFileSuccess() {
        try {
         String result =  mockMvc.perform(
              MockMvcRequestBuilders
                  .fileUpload("/file")
                  .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);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    

     编写文件下载接口

    package com.micro.fast.security.demo.controller;
    
    import org.apache.tomcat.util.http.fileupload.IOUtils;
    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.*;
    
    @RestController
    @RequestMapping("/file")
    public class FileController {
      /**
       * 处理文件上传
       * @param file
       */
      @PostMapping
      public  String  upload(MultipartFile file){
        File localfile = new File("/file/name");
        try {
          //将文件上传到本地路径
          file.transferTo(localfile);
        } catch (IOException e) {
          e.printStackTrace();
        }
        String fileInfo = "";
        fileInfo += file.getName()+file.getOriginalFilename()+file.getContentType();
        return fileInfo;
      }
    
      /**
       * 文件的下载
       * @param id
       * @param request
       * @param response
       */
      @GetMapping("/{id}")
      public void download(@PathVariable String id , HttpServletRequest request, HttpServletResponse response){
        try (InputStream inputStream = new FileInputStream(new File("/root/file/name"));
             OutputStream outputStream = response.getOutputStream();
        ){
          response.setContentType("application/x-download");
          //指定文件的名称
          response.addHeader("Content-Disposition","attachment;filename=test.txt");
          IOUtils.copy(inputStream,outputStream);
          outputStream.flush();
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    

    原文地址:https://blog.csdn.net/c_intmian/article/details/79543292

  • 相关阅读:
    php使用cookie来保存用户登录信息
    Linux下进程操作
    TortoiseSVN无法编辑日志信息的解决方法
    用DIV布局制作公告板
    HashMap的遍历
    实现文本滚动
    子DIV块中设置margintop时影响父DIV块位置的解决办法
    php使用session来保存用户登录信息
    javascript jquery ajax动态提交多个参数 api测试 拂晓风起
    javascript 处理返回json中的\u中文乱码问题(也不是乱码了,就是\u编码) 拂晓风起
  • 原文地址:https://www.cnblogs.com/jpfss/p/10968757.html
Copyright © 2011-2022 走看看