使用httpUrlConnection进行文件的读取和下载
一、实现的功能介绍
- 使用httpUrlConnection进行文件的读取;
- word模板数据的替换,并使用poi生成新的word文件
- 新文件上传到ftp服务器中,返回httpUrl地址,可根据此地址下载该word文件
二、pom.xml依赖
org.apache.poi
poi
3.15
org.apache.poi
poi-ooxml-schemas
3.15
org.apache.poi
poi-ooxml
3.15
org.apache.poi
poi-scratchpad
三、代码实现
/**
* 后台管理中下载用户协议,拿到ftp地址
* @param id
* @return
*/
@GetMapping("/sysprotocol/sysprotocoluser/download")
public ResponseObj download(Integer id) {
SysProtocolUser sysProtocolUser = null;
try {
try {
sysProtocolUser = sysProtocolUserService.findOne(id);
if (sysProtocolUser.getFtpUrl() != null) {
return ResponseObj.createSuccessResponse(sysProtocolUser.getFtpUrl());
}
} catch (Exception e) {
e.printStackTrace();
}
//如果是用户注册协议,且第一次下载,获取协议模板,并进行模板填充,生成用户协议,word上传到ftp服务器中
if (sysProtocolUser.getProtocolId() == 1) {
SysProtocol sysProtocol = sysProtocolService.selectById(sysProtocolUser.getProtocolId());
String protocolFtpUrl = sysProtocol.getFtpUrl();
URL url = new URL(protocolFtpUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");//设置请求方式
conn.setConnectTimeout(5000);//设置连接超时
conn.setDoInput(true);//是否打开输入流
conn.setDoOutput(true);//是否打开输出流
conn.connect();
int code = conn.getResponseCode();
//连接成功,进行文件读写操作
if (code == 200) {
//读取文件并写入到outpath中
String outpath = "";
try {
InputStream is = conn.getInputStream();
outpath = this.getClass().getResource("").getPath() + DateUtil.dateToDateFullString(DateUtil.getDate()) + ".doc";
FileOutputStream fos = new FileOutputStream(outpath);
byte[] buffer = new byte[1024 * 8];
int len = 0;
while ((len = is.read(buffer)) != -1) {
try {
fos.write(buffer, 0, len);
} catch (IOException e) {
e.printStackTrace();
}
}
fos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
//协议模板替换
String newpath = "";
try {
newpath = this.getClass().getResource("").getPath() + DateUtil.dateToDateFullString(DateUtil.getDate()) + ".doc";
FileInputStream fis = new FileInputStream(outpath);
HWPFDocument doc = new HWPFDocument(fis);
Range range = doc.getRange();
range.replaceText("{0}", sysProtocolUser.getUserPhone());
range.replaceText("{1}", sysProtocolUser.getProtocolUserid());
range.replaceText("{2}", DateUtil.dateToDateString(sysProtocolUser.getCreateTime()));
FileOutputStream fos = new FileOutputStream(newpath);
doc.write(fos);
fos.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
File file = new File(newpath);
InputStream fis = new FileInputStream(file);
String ftpUrl = ftpUtil.uploadFile(fis, doc.doDateFilePath(), doc.getDefaultFileName());
if (null != ftpUrl) {
sysProtocolUser.setFtpUrl(ftpUrl);
sysProtocolUserService.updateOne(sysProtocolUser);
new File(newpath).delete();
new File(outpath).delete();
return ResponseObj.createSuccessResponse(ftpUrl);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return ResponseObj.createErrResponse(ErrerMsg.ERRER100);
}