RestTemplate 发送Post请求传输图片(Base64),并接收请求存储图片至本地。

map必须为MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();否则会报错。

图片传输需要进行Base64进行转换,防止图片超过2M从而传输失败

 
@RequestMapping("/list")
	@ResponseBody
	public String PostForPic() {
		String url = "http://192.168.110.100:8001/getForPic";
		String path = this.getClass().getResource("/").getPath();
		String ImagePath = path + "static/test1.jpg";
		String base64 = convertFileToBase64(ImagePath);
 
		RestTemplate rest = new RestTemplate();
		MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
		headers.add("content-type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
		// headers.add("Accept", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
		// 请求体
		MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
		body.add("file", "picture");
		body.add("base64", base64);
		body.add("key", "123456");
 
		HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(body, headers);
		ResponseEntity<String> response = rest.postForEntity(url, httpEntity, String.class);
		String res = response.getBody();
		return res;
	}

convertFileToBase64转换方法 :

<dependency>
	<groupId>commons-codec</groupId>
	<artifactId>commons-codec</artifactId>
	<version>1.14</version>  
</dependency>
public String convertFileToBase64(String imgPath) {
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgPath);
            System.out.println("文件大小(字节)=" + in.available());
            data = new byte[in.available()];
            in.read(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // 对字节数组进行 Base64编码,得到 Base64编码的字符串
        String base64Str = Base64.encodeBase64String(data);
        return base64Str;
    }

接收Post请求:

//接受Post发送的pic并存入本地static
	@RequestMapping("/getForPic")
	@ResponseBody
	public void getPic(@RequestParam Map<String,String> map) {
		System.out.println("map"+map);
		String base64 = map.get("base64");
		
		byte[] bytes = Base64.decodeBase64(base64); // Base64解码
        // 使用 SpringBoot自带的 ClassUtils获取项目的根路径
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        FileOutputStream fis = null;
        try {
            fis = new FileOutputStream(path + "static/postFormData.jpg");
            fis.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
 
	}

在这里插入图片描述

package com.hope.demoexam.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.alipay.api.internal.util.file.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * @author: Mr.W
 * @date: 2024/3/29 22:25
 */
@Slf4j
@RestController
@RequestMapping("/fileManage")
public class FileManageController {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }


    @Resource
    RestTemplate restTemplate;

    @PostMapping("/upload")
    public String upload(@RequestParam("fileId") String fileId, @RequestParam(value = "file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String filePath = null;
        try {
            File tempFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), suffixName, new File("D:\\var"));
            File toFile = multiPartFileToFile(tempFile, file);
            //回调上传
            if (fileId.equals("1")) {
                // 创建请求头
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.MULTIPART_FORM_DATA);
                // 请求体
                MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
                body.add("file", new FileSystemResource(toFile));
                body.add("fileId", "2");
                HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity(body, headers);
                ResponseEntity<String> resp = restTemplate.postForEntity("http://127.0.0.1:7896/fileManage/upload", httpEntity, String.class);
                String body1 = resp.getBody();
                System.out.println("body1 = " + body1);
            }
            filePath = toFile.getPath();
            System.out.println("toFile = " + toFile.getPath());
        } catch (IOException e) {
            log.error("上传文件失败={}", ExceptionUtil.getMessage(e));
            e.printStackTrace();
        }
        return filePath;
    }

    /**
     * 将MultiPartFile转化为File
     *
     * @param target
     * @param multiFile
     * @return
     * @throws IOException
     */
    public static File multiPartFileToFile(File target, MultipartFile multiFile) throws IOException {
        multiFile.transferTo(target);
        return target;
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值