從Springboot項目中下載文件的具體過程

最近在做一個臨時的項目,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";
    }

訪問:http://127.0.0.1:8081/ymd/downApp 文件就下載下來瞭,本方法借鑒瞭 網絡上的一些文章

到此這篇關於從Springboot項目中下載文件的文章就介紹到這瞭,更多相關Springboot項目下載文件內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: