1. 程式人生 > >圖片上傳測試

圖片上傳測試

@Test
    public void uploadFilePublic1() throws Exception {
        File file = new File("D:/Document/BI/pic/aa201810232018.png");
        //檔案之外的引數
        //String key = OssUtils.createFileKey(file.getName(), null);
        MockMultipartFile firstFile = new MockMultipartFile("multipartFiles", "aa201810232018.png",     //注意multipartFiles一定要與public ResponseBean<Object> uploadImg(@RequestParam("multipartFiles") MultipartFile[] multipartFiles){相同
                MediaType.MULTIPART_FORM_DATA_VALUE, new FileInputStream(file));

        mockMvc.perform(MockMvcRequestBuilders.fileUpload("/custom/uploadImg")
                .file(firstFile)
                        .param("key", "keys")
                )//引數
                .andExpect(MockMvcResultMatchers.status().isOk());

    }
@ApiOperation(value = "圖片的上傳介面")
    @PostMapping(value = "/uploadImg")
    @ResponseBody
    public ResponseBean<Object> uploadImg(@RequestParam("multipartFiles") MultipartFile[] multipartFiles){
        ResponseBean<Object> responseBean = new ResponseBean<>();
        RsBody<Object> rsBody = new RsBody<>();
        List<ImageVO> imgList = new ArrayList<>();

        for (MultipartFile multi : multipartFiles) {
            System.out.println("---");
            ImageVO imageVO = new ImageVO();
            String name = multi.getOriginalFilename();
            //設定允許上傳檔案型別
            List<String> suffixList = Arrays.asList("jpg", "png");
            String suffix = name.substring(name.lastIndexOf(".") + 1, name.length());
            if (suffixList.contains(suffix.trim().toLowerCase())) {
                String url = OSSClientUtils.uploadImg2Oss(multi);
                System.out.println(url);
                imageVO.setUrl(url);
                imgList.add(imageVO);
            } else {
                continue;
            }
        }
        System.out.println(imgList);
        rsBody.setData(imgList);
        responseBean.setResponseBody(rsBody);
        return responseBean;
    }