通过url获取文件资源,用于服务器文件上传form-data方式
/**
* 通过url获取文件资源
*
* @param url 文件url
* @param fileName 文件名称
* @return
* @throws IOException
*/
public static ByteArrayResource getResourceByUrl(String url, String fileName) throws IOException {
// 通过url获取输入流
InputStream inputStream = getFileInputStream(url);
if (inputStream == null) {
return null;
}
// 读取输入流到字节数组
byte[] bytes = readBytes(inputStream);
// 将自己数组转为文件资源
return new ByteArrayResource(bytes) {
@Override
public String getFilename() {
// 指定文件名称
return fileName;
}
};
}
/*读取网络文件*/
private static InputStream getFileInputStream(String path) {
URL url = null;
try {
url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
return conn.getInputStream();
} catch (Exception e) {
logger.error("读取网络文件异常:" + path);
}
return null;
}
/**
* 读取输入流到字节数组
*
* @param in
* @return
* @throws IOException
*/
private static byte[] readBytes(InputStream in) throws IOException {
//读取字节的缓冲
byte[] buffer = new byte[1024];
//最终的数据
byte[] result = new byte[0];
int size = 0;
while ((size = in.read(buffer)) != -1) {
int oldLen = result.length;
byte[] tmp = new byte[oldLen + size];
if (oldLen > 0) {//copy 旧字节
System.arraycopy(result, 0, tmp, 0, oldLen);
}
//copy 新字节
System.arraycopy(buffer, 0, tmp, oldLen, size);
result = tmp;
}
return result;
}
版权声明:本文为weixin_44684303原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。