1、使用form表单上传文件

文件发送:

@Test
public void storeFile1() {
    File file = new File("D:\\test.txt");
    String uploadUrl = "http://127.0.0.1:8080/upload1";

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
    body.add("partFile", new FileSystemResource(file));

    HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(body, headers);
    URI uri = URI.create(uploadUrl);
    try {
        ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.POST, entity, String.class);
        logger.info("文件上传响应结果:{}", response.getBody());
    } catch (HttpClientErrorException | HttpServerErrorException e) {
        logger.error(e.getResponseBodyAsString());
    } catch (Exception e) {
        logger.error("文件上传失败", e);
    }
}

对应PostMan调用:

接收文件:

@ResponseBody
@PostMapping(path = "upload1", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Map<String, Object> upload1(@RequestPart("partFile") MultipartFile partFile) {
    Map<String, Object> back = new HashMap<>();
    try {
        String fileName = partFile.getOriginalFilename();
        File file = new File(fileName);
        file.createNewFile();
        FileUtils.writeByteArrayToFile(file, partFile.getBytes());
        logger.info("文件存储路径:{}", file.getAbsolutePath());
        back.put("sucess", true);
        back.put("message", "文件上传成功");
    } catch (Exception e) {
        logger.error("上传文件出错", e);
        back.put("sucess", false);
        back.put("message", "文件上传失败");
    }
    return back;
}

2、直接传输二进制数据(适用向oss、minio等文件文件存储服务)

发送数据:

@Test
public void storeFile2() {
    RestTemplate restTemplate = new RestTemplate();
    File file = new File("D:\\test.txt");
//    String uploadUrl = "http://your-bucket.oss-cn-guangzhou.aliyuncs.com/2022-10-26/cs.txt?Expires=16667815119&OSSAccessKeyId=LTAI5t8KipxMsdvSwxWB1Mw1&Signature=AzBjHIijczjlN%2Bl5Og6SlBuC%2BzA%3D";
    String uploadUrl = "http://127.0.0.1:8080/upload2/test.txt";

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

    byte[] byts;
    try {
        byts = FileUtils.readFileToByteArray(file);
    } catch (IOException e) {
        throw new RuntimeException("文件读取错误", e);
    }
    HttpEntity<byte[]> entity = new HttpEntity<>(byts, headers);
    URI uri = URI.create(uploadUrl);
    try {
//        restTemplate.put(uri, entity);
        ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.PUT, entity, String.class);
        logger.info("文件上传响应结果:{}", response.getBody());
    } catch (HttpClientErrorException | HttpServerErrorException e) {
        logger.error(e.getResponseBodyAsString());
    } catch (Exception e) {
        logger.error("文件上传失败", e);
    }
}

对应PostMan调用:

接收文件:

@ResponseBody
@RequestMapping(method = RequestMethod.PUT, path = "upload2/{fileName}", consumes = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public Map<String, Object> upload1(HttpServletRequest request, @PathVariable String fileName) {
    Map<String, Object> back = new HashMap<>();
    try {
        File file = new File(fileName);
        file.createNewFile();
        FileUtils.copyInputStreamToFile(request.getInputStream(), file);

        logger.info("文件存储路径:{}", file.getAbsolutePath());
        back.put("sucess", true);
        back.put("message", "文件上传成功");
    } catch (Exception e) {
        logger.error("上传文件出错", e);
        back.put("sucess", false);
        back.put("message", "文件上传失败");
    }
    return back;
}

 

注意:oss和mimio文件上传地址有特殊字符,需要用URI.create()进行处理

 

3、下载文件

public void downloadFile() throws IOException {
    RestTemplate restTemplate = new RestTemplate();
    String fileUrl = "http://your-bucket.oss-cn-guangzhou.aliyuncs.com/2022-11-11/b2ce6331e315.txt?Expires=1668150931&OSSAccessKeyId=LTAI5t8KipxMsdvSwxWB1Mw1&Signature=3%2BX%2BRhUIP4K23y7KEGaOIgG3ro4%3D";
    URI uri = URI.create(fileUrl);
    ResponseEntity<byte[]> response = restTemplate.getForEntity(uri, byte[].class);
    byte[] byts = response.getBody();
    FileUtils.writeByteArrayToFile(new File("D:\\test.txt"), byts);
}

 

posted on 2022-10-27 15:30  玄同太子  阅读(2306)  评论(0编辑  收藏  举报