从网络上下载文件到本地

 1 package com.example.demo.controller;
 2 
 3 import lombok.extern.slf4j.Slf4j;
 4 import org.springframework.http.MediaType;
 5 import org.springframework.stereotype.Controller;
 6 import org.springframework.util.FileCopyUtils;
 7 import org.springframework.web.bind.annotation.GetMapping;
 8 import org.springframework.web.bind.annotation.RequestMapping;
 9 import org.springframework.web.bind.annotation.ResponseBody;
10 
11 import javax.annotation.Resource;
12 import javax.servlet.http.HttpServletResponse;
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.net.MalformedURLException;
16 import java.net.URL;
17 import java.net.URLEncoder;
18 
19 @Controller
20 @Slf4j
21 @RequestMapping("/test15")
22 public class Test15Controller {
23 
24     @Resource
25     private HttpServletResponse response;
26 
27     @GetMapping("/fileDownLoad")
28     @ResponseBody
29     public void fileDownload() {
30         InputStream inputStream = null;
31         URL url = null;
32         try {
33             url = new URL("https://n.sinaimg.cn/ent/4_img/upload/1f0ce517/160/w1024h1536/20210413/0dad-knqqqmv1022299.jpg");
34             inputStream = url.openStream();
35             response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
36             response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("李勇亮.jpg", "UTF-8"));
37             // 使用工具类直接将文件的字节复制到响应输出流中
38             FileCopyUtils.copy(inputStream, response.getOutputStream());
39         } catch (MalformedURLException e) {
40             log.error("获取远程数据失败:", e);
41             e.printStackTrace();
42         } catch (IOException e) {
43             log.error("读取远程数据失败:", e);
44             e.printStackTrace();
45         }finally {
46             if (inputStream != null) {
47                 try {
48                     inputStream.close();
49                 } catch (IOException e) {
50                     log.error("关闭流失败:", e);
51                     e.printStackTrace();
52                 }
53             }
54         }
55     }
56 }

 

posted @ 2024-02-01 14:01  liyongliang的博客  阅读(10)  评论(0)    收藏  举报