- 服务器下载互联网返回文件到本地服务器
//MediaUrl String 原始媒体文件的 URL 地址。
String mediaUrl = "";
String url = mediaUrl+"?download_name="+name+"."+type;
int ec = FileDownload.downloadImage(url);
@Log
public class FileDownload {
public static int downloadImage(String fileUrl ) {
long l = 0L;
String path = null;
int ec = 0;
if (fileUrl != null) {
//下载时文件名称后缀
String fileName = fileUrl.substring(fileUrl.lastIndexOf("=")+1);
try {
String dataStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
//String uuidName = UUID.randomUUID().toString();
// = "resources/"+dataStr+"/"+uuidName+fileName;
// 准备文件夹,获取项目中upload文件夹的路径System.getProperty("user.dir")
String parentDir = System.getProperty("user.dir")+File.separator+"upload"+File.separator+dataStr;
//staticAndMksDir = Paths.get(ResourceUtils.getURL("classpath:").getPath(),"resources",dataStr).toString();
log.info("下载文件链接:"+fileUrl+"位置:"+parentDir + File.separator + fileName);
l=System.currentTimeMillis();
// System.getProperties().list(System.out);
HttpUtil.downloadFile(fileUrl, parentDir + File.separator + fileName);
log.info("下载文件"+fileName+"共使用:"+(System.currentTimeMillis()-l)+"ms");
} catch (Exception e) {
log.info("下载文件"+fileName+"失败:");
ec = 10001;
e.printStackTrace();
} finally {
}
}
return ec;
}
}
- 上传文件到其他服务器
File file = new File(localFile);
//restApiUrl
PostMethod filePost = new PostMethod(restApiUrl+"/download");
HttpClient client = new HttpClient();
try {
// 通过以下方法可以模拟页面参数提
Part[] parts = { new FilePart("file", file) };
filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
int status = client.executeMethod(filePost);
if (status == HttpStatus.SC_OK) {
log.info("上传视频到内网成功"+localFile);
return "";
} else {
log.info("上传视频到内网失败"+localFile);
return "error";
}
} catch (Exception ex) {
ex.printStackTrace();
return "error";
} finally {
filePost.releaseConnection();
}
- 服务器1接到服务器2返回的文件流,返回到互联网
@GetMapping("/queryMedia/{mediaName}")
public void queryMedia(@PathVariable("mediaName") String mediaName,HttpServletResponse response) throws Exception {
HttpRequestUtil.sendFileGet(ControllerConstant.INTRAURL+"tinyFile/"+mediaName, "",response);
}
public static void sendFileGet(String requestUrl, String param,HttpServletResponse response) throws Exception {
logger.info("发送get请求:"+requestUrl+"参数:"+param+"获取当前参数"+sysKey+sysCode);
URL u = new URL(requestUrl);
//注意:重点知识,此句判断用于信任所有的https请求
/*if("https".equalsIgnoreCase(u.getProtocol())){
//测试SslUtils
SslUtils.ignoreSsl();
}*/
String result = "";
BufferedReader in = null;
BufferedWriter out = null;
try {
String urlString = requestUrl + "?" + param;
URL url = new URL(urlString);
// 打开和URL之间的连接
URLConnection connection = url.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestProperty("PFPJ-SourceSysKey", sysKey);
connection.setRequestProperty("PFPJ-SourceSysCode", sysCode);
if(gray) {
connection.setRequestProperty("white", "true");
}
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
byte[] buffer = new byte[1024];
// FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
try {
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (bis != null) {
bis.close();
}
}
// logger.info("发送get请求:"+requestUrl+"参数:"+param+"返回信息:"+result);
} catch (Exception e) {
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
// return result;
}
- 上传所有格式的数据
@PostMapping("/upload/part")
@ResponseBody
public CommonResult uploadPart(Part file) {
CommonResult comm = new CommonResult();
String fileName = file.getSubmittedFileName();
System.out.println(fileName);
// String newName = System.currentTimeMillis()+"."+fileName.split(".")[1];
try {
file.write(fileName);
comm.setMsg(beforeMediaUrl+fileName);
}catch(Exception e) {
log.info(e.toString());
e.printStackTrace();
comm.setMsg("上传失败");
}
return comm;
}
@Component
public class TinyFileWebConfiguration implements WebMvcConfigurer {
@Value("${spring.servlet.multipart.location}")
private String filePath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 注意如果filePath是写死在这里,一定不要忘记尾部的/或者\\,这样才能读取其目录下的文件
registry.addResourceHandler("/**").addResourceLocations(
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/",
"file:/" + filePath,
"file:/home/psbcbj/corpwx/app/intranetfinancial-atlas/",
"classpath:/webapp/");
}
}