文件上传到远程接口
本地文件是暂存的,上传后要删除
fileTemporaryStoragePath 是文件在本地的存储路径
fileTempName 是文件的名称+类型,类似test.pdf
fileTemporaryStoragePath + fileTempName,是文件全路径
yxFile 是接口返回数据的接收对象
/**
* 文件上传到远程
* 上传后本地被删除
*
* @param fileTempName xxxx.pdf
* @return 上传到接口后的返回数据(文件地址)
*/
@Override
public String uploadFile(String fileTempName) {
log.info("上传文件:{}", fileTempName);
String yxFile = "";
String tempFilePath = fileTemporaryStoragePath + fileTempName;
File tempFile = new File(tempFilePath);
OutputStream out = null;
BufferedReader reader = null;
try {
if (!tempFile.exists() || !tempFile.isFile()) {
throw new IOException("文件不存在");
}
URL urlObj = new URL(officialWebsiteUploadFileUrl);
// 连接
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
/**
* 设置关键值
*/
con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false); // post方式不能使用缓存
// 设置请求头信息
con.setRequestProperty("charset", "UTF-8");
con.setRequestProperty("accept", "application/json");
con.setRequestProperty("Content-length", String.valueOf(tempFile.length()));
// 设置边界
String BOUNDARY = "----------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
// 请求正文信息
// 第一部分:
StringBuilder sb = new StringBuilder();
sb.append("--"); // 必须多两道线
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"file\";filename=\""
+ tempFile.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
// 获得输出流
out = new DataOutputStream(con.getOutputStream());
// 输出表头
out.write(head);
// 文件正文部分
// 把文件已流文件的方式 推入到url中
DataInputStream in = new DataInputStream(new FileInputStream(tempFile));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
// 结尾部分
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
out.write(foot);
out.flush();
out.close();
out = null;
//返回值
int resultCode = con.getResponseCode();
String msg = con.getResponseMessage();
if (200 != resultCode) {
log.info("返回值不是200,文件上传到远程接口异常:{}", msg);
} else {
log.info("返回值是200,文件上传到远程接口成功:{}", msg);
// 读取返回数据
StringBuffer strBuf = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
yxFile = strBuf.toString();
reader.close();
reader = null;
}
//删除本地文件
tempFile.delete();
} catch (Exception e) {
log.info("文件上传到远程接口异常:{}", e.getMessage());
} finally {
//关闭流
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return yxFile;
}