restTemplate上传文件
程序员文章站
2022-04-15 18:57:41
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.h....
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);
}
}
本文地址:https://blog.csdn.net/zhaoyahui_666/article/details/109643227