缺点:此方法接收文件参数后会建立个本地文件夹。如环境中不允许创建文件夹,请看另一篇接收文件参数后请求外部接口的文档。
@Autowired
private GatewayParams gatewayParams;
@Override
public String createbyfile (@RequestBody MultipartFile file,String title,String fileType){
MultiValueMap<String,Object> params = new LinkedMultiValueMap<>();
try {
params.add("file",new FileSystemResource(convert(file)));
} catch (IOException e) {
e.printStackTrace();
}
params.add("title",title);
params.add("fileType",fileType);
//请求接口要传的头参数
String appToken = gatewayParams.getGateDianZiToken();
String appSecret = gatewayParams.getGateDianZiSecret();
Date nowDate = new Date();
Long timestamp = nowDate.getTime();
double nonce = Math.random();
//MD5加密头内容
String signature= MD5Utils.stringToMD5(appToken+appSecret+timestamp.toString()+nonce);
//封装请求外部接口的请求头参数
HttpHeaders headers = new HttpHeaders();
headers.set("x-qys-accesstoken",appToken);
headers.set("x-qys-timestamp",timestamp.toString());
headers.set("x-qys-nonce",nonce+"");
headers.set("x-qys-signature",signature);
//外部接口的请求地址
String url =gatewayParams.getGateDianZiUrl() + "/v2/document/createbyfile";
HttpEntity<?> httpEntity = new HttpEntity<>(params,headers);
RestTemplate restTemplate =new RestTemplate();
//请求外部接口
ResponseEntity<JSONObject> response =restTemplate.postForEntity(url,httpEntity, JSONObject.class);
Object result =response.getBody();
if(result != null){
Map<String,Object> resultMap = (Map<String, Object>) result;
Map<String,Object> resultMap1=(Map<String, Object>)resultMap.get("result");
//合同ID
return (String) resultMap1.get("documentId");
}else {
return "";
}
}
//创建本地文件夹
public static File convert(MultipartFile file) throws IOException {
File convFile = new File("temp_image",file.getOriginalFilename());
if (!convFile.getParentFile().exists()) {
// 应修改为log输出
System.out.println("mkdir:" + convFile.getParentFile().mkdirs());
}
boolean fileBool=convFile.createNewFile();
if( !fileBool){
//应修改为log输出
System.out.println("创建文件夹失败");
}
try (FileOutputStream fos= new FileOutputStream(convFile);){
fos.write(file.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
return convFile;
}
MD5Utils是一个MD5加密的方法,是外部接口请求头约定需要的。
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Utils {
public static String stringToMD5(String plainText) {
byte[] secretBytes = null;
try {
secretBytes = MessageDigest.getInstance("md5").digest(
plainText.getBytes()
);
}
catch (NoSuchAlgorithmException e){
throw new RuntimeException("没有这个md5算法!");
}
String md5code = new BigInteger(1, secretBytes).toString(16);
for(int i = 0; i < 32 - md5code.length(); i++){
md5code = "0" + md5code;
}
return md5code;
}
}
private GatewayParams gatewayParams;是我配置记录的外部接口的信息,包括接口地址、token信息,密钥等。
以下几个都是外部接口请求头需要的认证,不具有普遍性,自行甄别参考哈。 headers.set("x-qys-accesstoken",appToken); headers.set("x-qys-timestamp",timestamp.toString()); headers.set("x-qys-nonce",nonce+""); headers.set("x-qys-signature",signature);