restful api上传文件(基础)-springboot

基于restful api格式的文件上传(只是上传到本地):

package com.nxz.controller;

import com.nxz.entity.FileInfo;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/file")
public class FileController {
    @PostMapping
    public FileInfo update(MultipartFile file) throws IOException {

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

        String holder = "G:\\0001-myproject\\mysecurity\\mysecurity-demo\\src\\main\\java\\com\\nxz\\controller";

        File localFile = new File(holder, new Date().getTime() + ".txt");

        file.transferTo(localFile);


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

}

测试用例:

   //伪造的mvc环境
    @Autowired
    private WebApplicationContext webApplicationContext;
    private MockMvc mockMvc;
    @Before
    public void before() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }
    @Test
    public void whenUploadSuccess() throws Exception {
        String file = mockMvc.perform(MockMvcRequestBuilders.fileUpload("/file")
                .file(new MockMultipartFile("file", "test.txt", "multipart/form-data", "hello".getBytes("UTF-8"))))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andReturn().getResponse().getContentAsString();
        System.out.println(file);
    }

测试用例执行完之后输出文件绝对路径:

{"path":"G:\\mysecurity\\mysecurity-demo\\src\\main\\java\\com\\nxz\\controller\\1556463660034.txt"}

下载:

 @GetMapping("/{id}")
    public void downLoad(@PathVariable String id,
                         HttpServletRequest request,
                         HttpServletResponse response) throws IOException {
        String holder = "G:\\0001-myproject\\mysecurity\\mysecurity-demo\\src\\main\\java\\com\\nxz\\controller";
        try (
                InputStream inputStream = new FileInputStream(new File(holder, id + ".txt"));
                OutputStream outputStream = response.getOutputStream();
        ) {
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=test.txt");//重新定义下载后名称
            //将文件输入流复制到输出刘超过年 commons-io依赖
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        }

    }

访问:http://localhost:8080/user/1

猜你喜欢

转载自www.cnblogs.com/nxzblogs/p/10787705.html