首页 > 其他分享 >使用RestTemplate上传文件

使用RestTemplate上传文件

时间:2022-10-27 15:48:14浏览次数:51  
标签:文件 RestTemplate back file new logger 上传

1、使用form表单上传文件

文件发送:

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

    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);
    }
}

接收文件:

@ResponseBody
@PostMapping(path = "upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Map<String, Object> upload(@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 storeFile1() {
    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";

    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);
    } catch (HttpClientErrorException | HttpServerErrorException e) {
        logger.error(e.getResponseBodyAsString());
    } catch (Exception e) {
        logger.error("文件上传失败", e);
    }
}

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

 

标签:文件,RestTemplate,back,file,new,logger,上传
From: https://www.cnblogs.com/zhi-leaf/p/16832434.html

相关文章