Android基于Http服务实现文件管理器

前言

马上快过年了,提前祝大家新年快乐,今天来写今年最后一篇文章。大家都知道手机自带的文件管理都有一个远程管理文件的功能,都是基于FTP服务实现,只要电脑端和手机端在同一局域网里,就可以访问手机里的文件,但是发现这种FTP远程文件管理有缺点:响应比较慢且整个页面刷新。本文基于Http服务实现一个远程文件管理,局部刷新,前端使用Ajax+H5实现,Android服务端使用AndServer。

实现效果图

PC端:

下载

Android端:

实现关键

  1. 在Android服务端编写两个接口:
  • 即获取SD卡存储目录的文件和目录
 /**
     * 返回文件列表
     *
     * @return
     */
    @GetMapping(path = "/list")
    List<FileInfo> getFileList(@RequestParam(name = "rootPath", required = false) String rootPath) {
        File file;
        if (TextUtils.isEmpty(rootPath)) {
            file = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
        } else {
            file = new File(rootPath);
        }
        List<FileInfo> fileInfoList = new ArrayList<>();
        if (!file.isDirectory()) {
            return fileInfoList;//不能返回空,否则前端收不到数据
        }
        File[] list = file.listFiles();
        if (list == null || list.length == 0) {
            return fileInfoList;
        }
        FileInfo fileInfo;
        for (File f : list) {
            String name = f.getName();
            fileInfo = new FileInfo();
            fileInfo.setName(name);
            fileInfo.setUrl(f.getAbsolutePath());
            fileInfo.setDateModified(f.lastModified());
            fileInfo.setDateModifiedString(TimeUtils.formatDateToStr(f.lastModified(), "yyyy/MM/dd aHH:mm:ss"));
            if (f.isFile()) {
                fileInfo.setIsDir(0);
                fileInfo.setSize(f.length());
                fileInfo.setSizeString(FileUtils.formatFileSize(f.length()));
            } else {
                fileInfo.setIsDir(1);
            }
            fileInfoList.add(fileInfo);
        }
        return fileInfoList;
    }

  • 下载文件的接口
 @PostMapping(path = "/download")
    ResponseBody download(HttpResponse response, @RequestParam(name = "rootPath", required = false) String rootPath) {

        if (TextUtils.isEmpty(rootPath)) {
            return new StringBody("文件路径为空");
        }
        try {
            File file = new File(rootPath);
            if (file.isFile() && file.exists()) {

                FileBody fileBody = new FileBody(file);
                response.setStatus(200);
                response.setHeader("Accept-Ranges", "bytes");
                response.setHeader("Content-Disposition", "attachment;fileName=" + file.getName());
                return fileBody;
            } else {
                return new StringBody("文件不存在或已经删除");
            }
        } catch (Exception e) {
            Logger.e("下载文件异常:" + e.getMessage());
            return new StringBody("下载文件异常:" + e.getMessage());
        }

    }
  1. 前端请求接口做数据展示和逻辑控制

小结

实现Http服务文件管理器整体不难,难在服务端的实现,非常感谢AndServer的作者,这个框架是基于底层库二次封装,提供了类似SpringMVC的注解接口,使得处理Http请求更简单。该示例还可以进步异步扩展,具体看有实际需求。

项目地址:https://github.com/kellysong/RemoteFileManager

猜你喜欢

转载自blog.csdn.net/u011082160/article/details/103885182