log.info("获取上传照片参数~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"+params);
JSONObject jsonObj = new JSONObject();
jsonObj.put("success", false);
String token=params.getParameter("token");
String workitemid=params.getParameter("workitemid");
String urlString=propertiesUtil.getKey("scene.errata.img.url");
String filePath="";
String res="";
log.info("上传照片地址"+urlString);
List<Attachment> attachments = attachmentService
.queryByWorkitemid(workitemid);
for(Attachment attachment: attachments) {
log.info("进来了1"+attachment.getKeyword()+attachment.getFilePath());
if(attachment.getKeyword().equals("箱体标签")) {
log.info("进来了2"+attachment.getKeyword()+attachment.getFilePath());
filePath=attachment.getFilePath();
}
}
log.info("上传照片路径"+filePath);
File file=new File(filePath);
String fileName = file.getName();
String boundary = Long.toHexString(System.currentTimeMillis());
try {
CloseableHttpResponse response = null;
HttpPost httpPost = new HttpPost(urlString);
httpPost.setHeader("Authorization",token);
httpPost.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
// 创建MultipartEntityBuilder
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// 设置字符编码
builder.setCharset(StandardCharsets.UTF_8);
// 模拟浏览器
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// 设置边界
builder.setBoundary(boundary);
// 设置multipart/form-data流文件
builder.addPart("file", new FileBody(file));
builder.addTextBody("fileName",fileName);
builder.addTextBody("fileDesc", fileName);
// application/octet-stream代表不知道是什么格式的文件
builder.addBinaryBody("media", file, ContentType.create("application/octet-stream"), fileName);
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
CloseableHttpClient httpClient = HttpClients.createDefault();
response = httpClient.execute(httpPost);
if (response != null && response.getStatusLine() != null && response.getStatusLine().getStatusCode() < 400) {
HttpEntity he = response.getEntity();
if (he != null) {
res = EntityUtils.toString(he, "UTF-8");
}
}
jsonObj.put("success", true);
jsonObj.put("data", res);
} catch (Exception e) {
e.printStackTrace();
jsonObj.put("success", false);
jsonObj.put("msg", "上传照片失败");
}
log.info("返回报文:" + jsonObj);
return jsonObj.toString();
java post请求以form-data格式上传file文件并请求接口
于 2024-04-16 11:59:12 首次发布