当前位置: 代码迷 >> 综合 >> springboot项目下载网络文件到本地,返回网络路径,简单实用
  详细解决方案

springboot项目下载网络文件到本地,返回网络路径,简单实用

热度:88   发布时间:2024-01-27 06:09:59.0

刚开始用这种方式

public static String downloadImage(String fileUrl ) {long l = 0L;String path = null;String staticAndMksDir = null;if (fileUrl != null) {//下载时文件名称String fileName = fileUrl.substring(fileUrl.lastIndexOf("."));DataInputStream fis = null;BufferedInputStream bis = null;OutputStream outputStream=null;BufferedOutputStream out=null;try {String dataStr = new SimpleDateFormat("yyyyMMdd").format(new Date());String uuidName = UUID.randomUUID().toString();path = "resources/images/"+dataStr+"/"+uuidName+fileName;staticAndMksDir = SpringPath.getStaticAndMksDir("resources", "images",dataStr);File file =new File(staticAndMksDir ,uuidName+fileName);file.createNewFile();outputStream = new FileOutputStream(file,true);out = new BufferedOutputStream(outputStream);URL url = new URL(fileUrl);fis = new DataInputStream(url.openStream());byte[] buffer = new byte[1024];bis = new BufferedInputStream(fis);int i = bis.read(buffer);while (i != -1) {out.write(buffer,0, i);i = bis.read(buffer);}} catch (Exception e) {e.printStackTrace();} finally {if (bis != null) {try {bis.close();} catch (IOException e) {e.printStackTrace();}}if (fis != null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}if(out!=null){try {out.close();} catch (IOException e) {e.printStackTrace();}}if(outputStream!=null){try {outputStream.close();} catch (IOException e) {e.printStackTrace();}}}}return path;}
}

在公司大牛指导下,改成了这种方式

import cn.hutool.http.HttpUtil;//需要导入的包public static String downloadImage(String fileUrl ) {long l = 0L;String path = null;String staticAndMksDir = null;if (fileUrl != null) {//下载时文件名称String fileName = fileUrl.substring(fileUrl.lastIndexOf("."));try {String dataStr = new SimpleDateFormat("yyyyMMdd").format(new Date());String uuidName = UUID.randomUUID().toString();path = "resources/images/"+dataStr+"/"+uuidName+fileName;staticAndMksDir = SpringPath.getStaticAndMksDir("resources", "images",dataStr);HttpUtil.downloadFile(fileUrl, staticAndMksDir + File.separator + uuidName + fileName);} catch (Exception e) {e.printStackTrace();} finally {}}System.out.println(System.currentTimeMillis()-l);return path;}

简单了很多, SpringPath.getStaticAndMksDir会返回项目的资源路径, 后面可直接拼上自己的路径, 可直接在网络路径中访问, 兼容本地启动和jar包启动方式