0
点赞
收藏
分享

微信扫一扫

restTemplate上传文件

西特张 2023-02-04 阅读 84


import lombok.extern.slf4j.Slf4j;
import net.go2global.common.core.bean.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
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.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @Author zyh
* @Date 2020/11/12 12:30
*/
@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {

@Autowired
private RestTemplate restTemplate;

private String url="http://127.0.0.1:9004/upload/uploadFile";

@PostMapping("/up")
public R up(
HttpServletRequest request,
HttpServletResponse response,
@RequestParam("file") MultipartFile file
) {

//设置请求头
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("multipart/form-data");
headers.setContentType(type);

//设置请求体,注意是LinkedMultiValueMap
MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
form.add("file", file.getResource());

//用HttpEntity封装整个请求报文
HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);

String s = restTemplate.postForObject(url, files, String.class);

return new R(s);
}

}

 

举报

相关推荐

0 条评论