做数据迁移将其他部门的视频地址转化到自己服务器下,生成自己的地址
private void modifyPath(List<M> records) {
List<M> updateRecords = new ArrayList<>();
try {
for (M pics : records) {
M m = new M();
m.setId(pics.getId());
boolean flag = updateVideoField(pics.getVideos(), m::setVideos);
if (flag) {
updateRecords.add(mProductPics);
}
}
if (!updateRecords.isEmpty()) {
batchUpdate(updateRecords);
}
} catch (Exception e) {
log.error("异常{}", e);
}
}
private boolean updateVideoField(String videoUrl, Consumer<String> setter) {
try {
if (StringUtils.isNotBlank(videoUrl) && videoUrl.startsWith("https://static")) {
String uploadUrl = uploadVideoFromUrl(videoUrl);
setter.accept(uploadUrl);
return true;
}
} catch (Exception e) {
log.error("异常{}", e);
}
return false;
}
public String uploadVideoFromUrl(String videoUrl) {
File tempFile = null;
try {
InputStream videoStream = getVideoStream(videoUrl);
if (videoStream == null) {
throw new KyException("视频不存在");
}
String fileName = videoUrl.substring(videoUrl.lastIndexOf("/") + 1);
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
tempFile = File.createTempFile(fileName.replace("." + suffix, ""), "." + suffix);
try (FileOutputStream fos = new FileOutputStream(tempFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = videoStream.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
}
if (!tempFile.exists()) {
throw new IOException("临时文件未创建: " + tempFile.getAbsolutePath());
}
return upload(tempFile);
} catch (Exception e) {
log.error("视频上传异常!", e);
throw new KyException("视频上传失败: " + e.getMessage());
} finally {
if (tempFile != null && tempFile.exists()) {
tempFile.delete();
}
}
}
private InputStream getVideoStream(String videoUrl) throws IOException {
URL url = new URL(videoUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("视频不可访问,HTTP 响应码: " + connection.getResponseCode());
}
return connection.getInputStream();
}
private String upload(File uploadFile) {
try {
return fileService.upload(uploadFile);
} finally {
uploadFile.delete();
}
}