java确定若干个网络素材,打包为zip软件转载

原创
小哥 3年前 (2022-12-30) 阅读数 22 #大杂烩

根据项目要求,需要存储多个url地址图片,打包为zip下载下来

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

public void download(HttpServletRequest request, HttpServletResponse response){

try {

String downloadFilename = "中文.zip" ; //文件的名称

downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8" ); //转换中文,否则可能会产生乱码。

response.setContentType( "application/octet-stream" ); // 指明response的返回对象是文件流

response.setHeader( "Content-Disposition" , "attachment;filename=" + downloadFilename); // 设置下载框中默认显示的文件名

ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());

String[] files = new String[]{ "http://xxxx/xx.jpg" , "http://xxx/xx.jpg" };

for ( int i= 0 ;i<files.length;i++) {

URL url = new URL(files[i]);

zos.putNextEntry( new ZipEntry(i+ ".jpg" ));

//FileInputStream fis = new FileInputStream(new File(files[i]));

InputStream fis = url.openConnection().getInputStream();

byte [] buffer = new byte [ 1024 ];

int r = 0 ;

while ((r = fis.read(buffer)) != - 1 ) {

zos.write(buffer, 0 , r);

}

fis.close();

}

zos.flush();

zos.close();

} catch (UnsupportedEncodingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除