龙空技术网

从Springboot项目中下载文件的具体过程

Java盘鱼宴 161

前言:

而今你们对“java实现文件下载到下载盘”大概比较看重,兄弟们都想要学习一些“java实现文件下载到下载盘”的相关知识。那么小编也在网上网罗了一些关于“java实现文件下载到下载盘””的相关知识,希望小伙伴们能喜欢,姐妹们一起来学习一下吧!

最近在做一个临时的项目,APP端在检测到程序有更新时,需要去后台下载新的安装包。具体过程如下:

controller层:

/**    * 下载app    * @param response    */   @RequestMapping("downApp")   @ResponseBody   public void Download(HttpServletResponse response) {       String fileName ="wuye.apk";       String result = FileUtil.downloadFile(response, fileName);       log.info("app包下载结果:",result);   }

工具类:

public class FileUtil {     public static String downloadFile(HttpServletResponse response, String fileName) {        File path =null;        response.setHeader("content-type","application/octet-stream");        response.setContentType("application/octet-stream");        try {            response.setHeader("Content-Disposition","attachment;filename=" + java.net.URLEncoder.encode(fileName,"UTF-8"));        }catch (UnsupportedEncodingException e2) {            e2.printStackTrace();        }        byte[] buff =new byte[1024];        BufferedInputStream bis =null;        OutputStream os =null;        try {            path =new File(ResourceUtils.getURL("classpath:").getPath());            os = response.getOutputStream();            bis =new BufferedInputStream(new FileInputStream(new File(path +"/doc/" + fileName)));            int i = bis.read(buff);            while (i != -1) {                os.write(buff,0, buff.length);                os.flush();                i = bis.read(buff);            }        }catch (FileNotFoundException e1) {            //e1.getMessage()+"系统找不到指定的文件";            return "系统找不到指定的文件";        }catch (IOException e) {            e.printStackTrace();        }finally {            if (bis !=null) {                try {                    bis.close();                }catch (IOException e) {                    e.printStackTrace();                }            }        }        return "success";    }

希望大家可以支持一下哦!谢谢大家支持!需要资料的小伙伴可以私信【Java】获取哦!

标签: #java实现文件下载到下载盘