读取本地文件上传到数据库

来源:互联网 发布:如何调用数组方法 编辑:程序博客网 时间:2024/06/01 10:15

public void update(String id) throws ClientProtocolException, IOException{

//获取本地文件

File filePath=new File("F:/aa");
File[] file=filePath.listFiles();
for (File file2 : file) {
CloseableHttpClient httpclient = HttpClients.createDefault();
InputStream inputStream=new FileInputStream(file2);
String originalFilename1 = file2.getName();
String originalFilename=originalFilename1.substring(0, originalFilename1.indexOf("."));
XrCandidate candidate=xrCandidateService.getxr(originalFilename);
// 原来的
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", inputStream, ContentType.MULTIPART_FORM_DATA,
originalFilename);// 文件流
builder.addTextBody("filename", originalFilename);// 类似浏览器表单提交,对应input的name和value

HttpPost httpPost = new HttpPost("http://localhost:8080/file/uploadPic");
httpPost.setEntity(builder.build());
// 发起请求 并返回请求的响应
CloseableHttpResponse response = httpclient.execute(httpPost);
String josns = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
JSONObject jsonObject = JSONObject.fromObject(josns);
String reCP = jsonObject.get("fid").toString();
if ( reCP != null) {
//reCP = jsonObject.get("fid").toString();
//System.out.println(reCP);
candidate.setPhoto(reCP);
}
xrCandidateService.updateByKey(candidate);
}

}