欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

通过超链接下载文件

程序员文章站 2022-05-06 17:18:56
...

java通过超链接下载文件

准备工作
//获取文件根目录
/**
* 获取根目录
* @return
*/
-public String getRootDirectory(){
File f = new File(DownloadCore.class.getResource("/").getPath());
String string = f.toString();
int hnwg = string.indexOf(“hnwg”);
System.out.println(hnwg);
System.out.println(string);
System.out.println(string.substring(0,hnwg+4));
String path = string.substring(0, hnwg + 4);
return path;
}

//利用递归获取一个目录下的所有文件夹
/**
* 传入路径根集合获取路径下所有文件
* @param path
* @param listFileName
*/

  • public void getAllFileName(String path, ArrayList listFileName) {
    File file = new File(path);
    File[] files = file.listFiles();
    String[] names = file.list();
    if (names != null) {
    String[] completNames = new String[names.length];
    for (int i = 0; i < names.length; i++) {
    completNames[i] = path + names[i];
    }
    listFileName.addAll(Arrays.asList(completNames));
    }
    for (File a : files) {
    if (a.isDirectory()) {//如果文件夹下有子文件夹,获取子文件夹下的所有文件全路径。
    getAllFileName(a.getAbsolutePath() + “\”, listFileName);
    }
    }
    }

//对比进行找到自己的资源
/**
* 获取需要文件
* @param file
* @param listFileName
* @return
*/

  • public String getPath(String file,ArrayList listFileName){

    for (String name : listFileName) {
    
        if (name.contains(file)){
    
            return name;
        }
    }
    return "";
    

    }

在Control我用的是springmvc下载的方法

-public ResponseEntity<byte[]> download(HttpServletRequest request,String name) throws IOException {

    System.out.println(name);
    String rootDirectory = downloadCore.getRootDirectory();
    ArrayList<String> listFileName = new ArrayList<String>();
    downloadCore.getAllFileName(rootDirectory,listFileName);
    String path = downloadCore.getPath(name, listFileName);

    System.out.println("结果路径"+path);
    File file = new File(path);
    byte[] body = null;
    InputStream is = new FileInputStream(file);
    body = new byte[is.available()];
    is.read(body);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Disposition", "attchement;filename=" + file.getName());
    HttpStatus statusCode = HttpStatus.OK;
    ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
    return entity;
}