105. File Uploading and Downloading - dkkahm/study-springfamework5 GitHub Wiki

Uploading Controller

@Controller
@RequestMapping("/image")
public class ImageController {
    private final ImageService imageService;

    public ImageController(ImageService imageService) {
        this.imageService = imageService;
    }

    @GetMapping
    public String getImageForm() {
        return "imageform";
    }

    @PostMapping
    public String handleImagePost(@RequestParam("imagefile") MultipartFile file) {
        imageService.saveImageFile(file);
        return "redirect:/image/show";
    }

    @GetMapping("/show")
    public String showImage() {
        return "showimage";
    }
}

Uploading Test

@ExtendWith(MockitoExtension.class)
class ImageControllerTest {
    @Mock
    ImageServiceImpl imageService;

    @InjectMocks
    ImageController imageController;

    MockMvc mockMvc;

    @BeforeEach
    void setUp() {
        mockMvc = MockMvcBuilders.standaloneSetup(imageController).build();
    }

    @Test
    void getImagePage() throws Exception {
        mockMvc.perform(get("/image"))
                .andExpect(status().isOk())
                .andExpect(view().name("imageform"));
    }

    @Test
    void postImage() throws  Exception {
        MockMultipartFile multipartFile = new MockMultipartFile("imagefile", "testing.txt", "text/plain", "Spring Framework Guru".getBytes());

        mockMvc.perform(multipart("/image").file(multipartFile))
                .andExpect(status().is3xxRedirection());
                // .andExpect(header().string("Location", "/recipe/1/show"));

        verify(imageService).saveImageFile(eq(multipartFile));
    }
}

Downloading Controller

    @GetMapping("/theimage")
    public void renderImage(HttpServletResponse response) throws IOException {
        byte[] byteArray = imageService.getImage();

        response.setContentType("image/jpeg");
        InputStream is = new ByteArrayInputStream(byteArray);
        IOUtils.copy(is, response.getOutputStream());
    }

Downloading Test

    @Test
    public void renderImageTest() throws Exception {
        String s = "fake image text";

        when(imageService.getImage()).thenReturn(s.getBytes());

        MockHttpServletResponse response = mockMvc.perform(get("/image/theimage"))
                .andExpect(status().isOk())
                .andReturn().getResponse();

        byte[] responseBytes = response.getContentAsByteArray();

        assertEquals(s.getBytes().length, responseBytes.length);
    }