简单的基于tomcat+spring的Java文件分享代码

使用了spring boot2搭建项目,这个软件非常简单、简陋就一个html界面,完全没有权限控制,纯粹的是用作个人用途,只是本人写了用来共享电脑上的文件到平板和手机上用的。

使用了Java8

https://github.com/tianxiadaoshu/fileshare

  • 2019/3/28 增加了多文件上传、删除文件(夹)、新建文件夹功能

简单的基于tomcat+spring的Java文件分享代码

 

简单的基于tomcat+spring的Java文件分享代码

软件使用了10086端口

代码:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>licx</groupId>
    <artifactId>fileshare</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>fileshare</name>
    <description>a file share wed application</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

FileController.java

package licx.fileshare.Controller;

import licx.fileshare.Domain.FileInfor;
import licx.fileshare.Service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.File;
import java.util.Date;
import java.util.List;

@Controller
public class FileController {

    @Autowired
    private FileService fileService;

    @GetMapping("/")
    public String getInitFiles(Model model){
        List<FileInfor> fileInforList = fileService.getInitFiles();
        model.addAttribute("parent_url", "#");
        model.addAttribute("cur_url", "root");
        model.addAttribute("fileList", fileInforList);
        return "index";
    }

    @GetMapping("/dir/get")
    public String getSomeDirectory(String destination, Model model){
        List<FileInfor> fileInforList = fileService.getDir(destination);
        String parentUrl = fileService.getParentDir(destination);
        model.addAttribute("parent_url", parentUrl);
        model.addAttribute("fileList", fileInforList);
        model.addAttribute("cur_url", destination);
        return "index";
    }


    @GetMapping("/download/file")
    public ResponseEntity<FileSystemResource> downloadFile(String destination) {
        return exportFile(new File(destination));
    }

    private ResponseEntity<FileSystemResource> exportFile(File file) {

        if (file == null) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + file.getName());
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));

        return ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(MediaType.parseMediaType("application/octet-stream")) .body(new FileSystemResource(file));
    }

}

 

FileInfor.java

package licx.fileshare.Domain;

public class FileInfor {
    private String name;
    private boolean directory;
    private String absolutelyUrl;

    public FileInfor() {
    }

    public FileInfor(String name, boolean directory, String absolutelyUrl) {
        this.name = name;
        this.directory = directory;
        this.absolutelyUrl = absolutelyUrl;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isDirectory() {
        return directory;
    }

    public void setDirectory(boolean directory) {
        this.directory = directory;
    }

    public String getAbsolutelyUrl() {
        return absolutelyUrl;
    }

    public void setAbsolutelyUrl(String absolutelyUrl) {
        this.absolutelyUrl = absolutelyUrl;
    }

    @Override
    public String toString() {
        return "FileInfor{" +
                "name='" + name + '\'' +
                ", directory=" + directory +
                ", absolutelyUrl='" + absolutelyUrl + '\'' +
                '}';
    }
}

FileService.java

package licx.fileshare.Service;

import licx.fileshare.Domain.FileInfor;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class FileService {

    public List<FileInfor> getInitFiles(){
        File[] fileList = File.listRoots();
        if (fileList == null || fileList.length == 0) {
            return null;
        }
        return fileListToFileInforList(fileList);
    }

    public String getParentDir(String destination){
        File file = new File(destination);
        return file.getParent();
    }

    public List<FileInfor> getDir(String destination){
        File parentFile = new File(destination);
        File[] children = parentFile.listFiles();
        if (children == null || children.length == 0) {
            return null;
        }
        return fileListToFileInforList(children);
    }

    private List<FileInfor> fileListToFileInforList(File[] files){
        List<FileInfor> fileInforList = new ArrayList<>();
        for (File file : files) {
            String a_path = file.getAbsolutePath();
            String path = a_path.replace("\\", "/");
            fileInforList.add(new FileInfor(file.getName(), file.isDirectory(), path));
        }
        return fileInforList;
    }

//    private ArrayList<File> getDiskInformation() {
//
//        File[] disks = File.listRoots();
//        if (disks.length == 0) {
//            return null;
//        }
//
//        return new ArrayList<>(Arrays.asList(disks));
//    }
}

application.properties


server.port=10086

 

index.html

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" xmlns:th="http://www.thymeleaf.org"> <!--<![endif]-->
<head>
    <title>文件共享</title>
    <meta charset="UTF-8"> <!-- for HTML5 -->
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" type="text/css" th:href="@{/file/assets/css/bootstrap.min.css}">
    <script type="text/javascript" th:src="@{/file/assets/js/bootstrap.min.js}"></script>
    <script type="text/javascript" th:src="@{/file/js/jquery.min.js}"></script>
</head>

<body>
<h1 align="center" th:text="${'当前路径:' + cur_url}"></h1>
<div class="container" style="width: 600px;height: 600px;">

    <table class="table table-hover">
        <tr>
            <th>文件名</th>
            <th>文件类型</th>
            <th>下载</th>
        </tr>
        <tr align="center">
            <td colspan="3"><button th:onclick="getDir([[${parent_url}]])">上级目录</button></td>
        </tr>
        <tr th:each="file:${fileList}">
            <td>
                <span th:if="${file.directory eq true}">
                    <button th:text="${'文件夹名:' + file.getName()}"
                            th:onclick="getDir([[${file.absolutelyUrl}]])"></button>
                </span>
                <span th:if="${file.directory eq false}">
                    <button th:text="${'文件名:' + file.getName()}" ></button>
                </span>

            </td>
            <td>
                <span th:if="${file.directory eq true}">文件夹</span>
                <span th:if="${file.directory eq false}">文件</span>
            </td>
            <td >
                <span th:if="${file.directory eq true}"><span>无法直接下载文件夹</span></span>
                <span th:if="${file.directory eq false}">
                    <button th:onclick="download_file([[${file.absolutelyUrl}]])">下载文件</button>
                </span>
            </td>
        </tr>
    </table>
</div>
</body>
<script>

    function getDir(des_url) {
        if (des_url ==="#"){
            return null;
        }
        if (des_url === null){
            window.location.href="/";
        }
        var tem_url = des_url.toString();
        var url = tem_url.replace("\\", "/");
        window.location.href="/dir/get?destination=" + url + "/";
    }

    function download_file(des_url) {
        var tem_url = des_url.toString();
        var url = tem_url.replace("\\", "/");
        window.location.href="/download/file?destination=" + url;
    }
</script>
</html>