/**
* @author BNTang
* @date Created in 2020/12/1 19:49
* @description 根据URL地址动态加载URL返回的文件信息
*/
public class DownloadUrlFileUtils {
/**
* 将 url 返回的文件转变为 MultipartFile对象
*
* @param url 地址
* @param fileName 文件名称
* @return 转换结果
*/
public static MultipartFile createFileItem(String url, String fileName) {
FileItem item = null;
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url + "/" + fileName).openConnection();
conn.setReadTimeout(30000);
conn.setConnectTimeout(30000);
// 设置应用程序要从网络连接读取数据
conn.setDoInput(true);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = conn.getInputStream();
FileItemFactory factory = new DiskFileItemFactory(16, null);
String textFieldName = "downloadFile";
item = factory.createItem(textFieldName, ContentType.APPLICATION_OCTET_STREAM.toString(), false, fileName);
OutputStream os = item.getOutputStream();
int bytesRead;
byte[] buffer = new byte[OperatingUnsoldConstant.READ_SIZE];
while ((bytesRead = is.read(buffer, OperatingUnsoldConstant.ZERO, OperatingUnsoldConstant.READ_SIZE)) != -1) {
os.write(buffer, OperatingUnsoldConstant.ZERO, bytesRead);
}
os.close();
is.close();
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("file download error");
}
if (item != null) {
return new CommonsMultipartFile(item);
}
return null;
}
}