//通过url地址下载附件再把附件传到另外一台服务器
public static void main(String[] args) throws IOException, InterruptedException {
//filePath这里写死,实际是从数据库里面读取,这里数据库读取到的多个附件是用,分割
String filePath="xxzgoafiles/wh/whseal/2210/决策生产组对数总结_1666764269633.docx" +
",xxzgoafiles/wh/whseal/2210/档案管理系统技术服务合同(最终稿)_1666764297216.doc";
//判断有没有附件
boolean hasfile = Pattern.compile("\\d{4}/").matcher(StringUtils.isNotBlank(filePath)?filePath:"").find();
String[] paths = new String[0];
if(hasfile) {
//注意,由于使用,分割多个附件,而且他也可以在附件名字中使用,所以这里分割的时候不能直接用它(,)来分割,
//如果用,分割如果附件名带,就出错了.换成前台不会使用到的东西分割.(这里的whxxwjg,你可以更复杂.)
filePath=filePath.replaceAll("(,)?(xxzgoa)?files","whxxwjg$2files");
paths = filePath.split("whxxwjg");
for (String path : paths) {
if(path.length()<10)continue;
String fileName=FileUtil.getName(filePath);
HashMap<String, Object> paramMap = new HashMap<>();
String urlPath="http://www.xxx.com/" + URLUtil.encode(path);
URL url = new URL(urlPath);
URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();//获取附件
File file=new File(fileName);
FileOutputStream otfile = new FileOutputStream(file);
IOUtils.copy(stream,otfile); //复制
stream.close();
otfile.close(); //关闭
paramMap.put("file",FileUtil.file(file));
String fileUrl="https://www.otherserver.com/stampInterface/file/getDownLoadFile?" +
"caseId=WKK2022&name=" + URLUtil.encode(fileName);
if(FileUtil.exist(file)) { //文件存在的话传到另外一台服务器
String res = HttpUtil.post(fileUrl, paramMap);
FileUtil.del(file.getAbsoluteFile()); //删除下载的临时文件
System.out.println(res);
}
}
}
}
用到的库
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.regex.Pattern;