导包
import com.alibaba.fastjson.JSONObject;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
本地文件上传
@Test
public void localPost() throws FileNotFoundException {
private String url = "http://xxx.xxx.xxx.xxx:8188/uploadfile4picture";
private String filePath = "C:\\Users\\rwto\\Desktop\\测试\\图片\\a.jpg";
RestTemplate rest = new RestTemplate();
FileSystemResource resource = new FileSystemResource(new File(filePath));
MultiValueMap<String,Object> param = new LinkedMultiValueMap<String,Object>();
param.add("file", resource);
String string = rest.postForObject(url, param, String.class);
JSONObject jsonObject = JSONObject.parseObject(string);
JSONObject data = JSONObject.parseObject(jsonObject.getString("data"));
System.out.println(data.getString("file_uri"));
}
通过文件流上传
@Test
public void streamPost() throws IOException {
private String url = "http://xxx.xxx.xxx.xxx:8188/uploadfile4picture";
private String filePath = "C:\\Users\\rwto\\Desktop\\测试\\图片\\a.jpg";
RestTemplate rest = new RestTemplate();
final FileInputStream in = new FileInputStream(new File(filePath));
Resource resource = new InputStreamResource(in){
@Override
public long contentLength() throws IOException {
long size = in.available();
return size;
}
@Override
public String getFilename(){
return "a.jpg";
}
};
MultiValueMap<String,Object> param = new LinkedMultiValueMap<String,Object>();
param.add("file", resource);
String string = rest.postForObject(url, param, String.class);
JSONObject jsonObject = JSONObject.parseObject(string);
JSONObject data = JSONObject.parseObject(jsonObject.getString("data"));
System.out.println(data.getString("file_uri"));
}