本章主要介绍怎么通过写一个java程序来获取远程服务器的图片,并把图片压缩到压缩包里并下载下来。前提是,图片的名称是有规律的,比如都是数字组成,既然都是数字组成的,那么就可以通过for循环来实现,比如下载文件名为1.png到1000.png的图片。
当我们下载服务器https://com.example/img/item/下的图片xxx.png,如果图片不存在,下面这句代码会发生异常,发生异常时直接使用continue跳过即可,继续我们的for循环。
inputStream = connection.getInputStream();
这种方式的优缺点如下:
优点:代码简单,没有使用非常复杂的API
缺点:速度很慢,因为要在for循环里频繁创建对象
@RestController
@Api(tags = "用户控制器类")
@RequestMapping(path = "/user", produces="application/json;charset=utf-8")
public class UserController {
@ApiOperation("获取图片资源")
@RequestMapping(value = "/getResources", method = RequestMethod.GET)
public void getResources(HttpServletResponse response, int from, int to) {
ZipOutputStream outputStream = null;
InputStream inputStream = null;
try {
StringBuilder filename = new StringBuilder();
// 压缩文件夹名:"图片资源" + from + "-" + to + ".zip"
StringBuilder zipName = new StringBuilder();
zipName.append("图片资源");
zipName.append(from);
zipName.append("-");
zipName.append(to);
zipName.append(".zip");
// 文件名中文乱码问题
String fileName = URLEncoder.encode(zipName.toString(), "utf-8");
// 设置响应头
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
ServletOutputStream sos = response.getOutputStream();
outputStream = new ZipOutputStream(sos);
// 遍历创建URL
for (int i = from; i <= to; i++) {
if (filename.length() > 0) {
filename.delete(0, filename.length());
}
filename.append("/img/item/").append(i).append(".png");
try {
URL url = new URL("https", "com.example", filename.toString());
inputStream = url.openConnection().getInputStream();
} catch (IOException e) {
continue;
}
outputStream.putNextEntry(new ZipEntry(i + ".png"));
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
}
} catch (IOException ignored) {}
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException ignored) {}
}
}
如果有更简单高效的方法,欢迎在评论区讨论~