Java文件中转

文件之间传送,有时候需要微信之类的中转,太麻烦了,不如做个服务器当作文件服务器来使用。

前端Vue+element-ui 后端spring

1、前端页面

html 复制代码
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!--360浏览器优先以webkit内核解析-->
    <title>CSDM</title>
    <link rel="shortcut icon" href="favicon.ico">
    <link href="../static/css/bootstrap.min.css" th:href="@{/css/bootstrap.min.css}" rel="stylesheet"/>
    <link href="../static/css/font-awesome.min.css" th:href="@{/css/font-awesome.min.css}" rel="stylesheet"/>
    <link href="../static/css/style.min.css" th:href="@{/css/style.min.css}" rel="stylesheet"/>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>

<body class="gray-bg">
<div id="app">
    <el-main width="50vh">
        <div style="height: 80%"></div>
        <div class="block">
            <el-upload
                    class="upload-demo"
                    drag
                    action="localhost:9082/upload/upload"
                    multiple>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传jpg/png文件,且不超过500kb</div>
            </el-upload>
        </div>
    </el-main>
    <h1>
        下载列表
    </h1>
    <div v-for="item in this.fileList">
        <a style="color:cornflowerblue;" @click="getFileByPath(item)">{{item}}</a>
    </div>
</div>
<script type="module">
    import axios from 'axios';
</script>
<script>
    var app = new Vue({
        el: '#app',
        data() {
            return {
                inputForm: {
                    id: '',
                    name: '',
                    number: '',
                    contactPerson: '',
                    type: '',
                    phone: '',
                    fileUrl: ''
                },
                fileList: [],
                file: {url: '', name: ''},
            }
        },
        created() {
            this.refreshList();
        },
        methods: {
            // 获取数据列表
            async refreshList() {
                try {
                    const response = await axios.get('http://localhost:9082/upload/getFilePath');
                    console.log(response.data);
                    this.splitFileUrl(response.data);
                } catch (error) {
                    console.error('Error fetching data:', error);
                }
            },
            async getFileByPath(fileName) {
                const link = document.createElement('a');
                link.href = `http://localhost:9082/upload/getFileByPath/?fileName=${encodeURIComponent(fileName)}`;
                link.download = fileName; // 设置下载文件的名称
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                console.log(link)
            },
            splitFileUrl(inputForm) {
                this.fileList = []; // 确保在数组上操作的是this.fileList
                if (Array.isArray(inputForm)) { // 检查inputForm是否是数组
                    inputForm.forEach(filePath => { // 遍历数组中的每个文件路径
                        const pathParts = filePath.split('\\'); // 使用split分割路径
                        const fileNameWithExtension = pathParts.pop(); // 获取文件名和扩展名
                        const [fileName, extension] = fileNameWithExtension.split('.'); // 使用split分割文件名和扩展名
                        this.fileList.push(fileName + "." + extension); // 将文件名+扩展名添加到this.fileList中
                    });
                } else {
                    console.error('Input form is not an array as expected.');
                }
            },
        },
    });
</script>
</body>
</html>

共有三个方法:

refreshList 获取其指定路径下的文件名称,getFilePath返回所有的文件名称

splitFileUrl 对文件名字做切割

getFileByPath 获取指定名字的文件

上传文件用了 el-upload action调用上传的接口

2、Controller层接口

java 复制代码
@Controller
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    UploadService uploadService;

    //上传页面
    @GetMapping("uploadView")
    public String uploadFileView() {
        return "module/upload";
    }

    //上传文件
    @PostMapping("upload")
    @ResponseBody
    public void uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        System.out.println(file.getName());
        uploadService.UploadFile(file);
    }
    
    //获取文件路径
    @GetMapping("getFilePath")
    @ResponseBody
    public List<String> findFilePath() {
        return uploadService.findFilePath();
    }
    
    //获取文件
    @GetMapping("getFileByPath")
    public ResponseEntity<Resource> downloadFile(@RequestParam("fileName")String fileName) throws IOException {
        return uploadService.getFileByPath(fileName);
    }
}

3、Service接口

java 复制代码
public interface UploadService {
    void UploadFile(MultipartFile file) throws IOException;

    List<String> findFilePath();

    ResponseEntity<Resource> getFileByPath(String fileName) throws IOException;
}

4、Impl实现类

java 复制代码
@Service
public class UploadServiceImpl implements UploadService {

    // 获取配置文件中的文件路径,根据实际需求可替换
    @Value("${ruoyi.uploadFile}")
    String profile;

    //上传文件
    @Override
    public void UploadFile(MultipartFile file) throws IOException {
        // 确保profile目录存在
        File fileDirectory = new File(profile);
        if (!fileDirectory.exists()) {
            boolean result = fileDirectory.mkdirs();
            if (result) {
                System.out.println("目录创建成功: " + profile);
            } else {
                System.out.println("目录创建失败: " + profile);
                throw new IOException("无法创建目录: " + profile);
            }
        }

        // 使用MultipartFile的原始文件名
        String originalFilename = file.getOriginalFilename();
        String targetFilePath = fileDirectory.getAbsolutePath() + File.separator + originalFilename;
        File targetFile = new File(targetFilePath);

        try {
            // 将MultipartFile保存到指定文件
            file.transferTo(targetFile);
            System.out.println("文件已成功保存到指定目录: " + targetFile.getAbsolutePath());
        } catch (IOException e) {
            throw new IOException("保存文件到指定目录时出错: " + targetFile.getAbsolutePath(), e);
        }
    }

    //找到当前路径下的文件名
    @Override
    public List<String> findFilePath() {
        Path profilePath = Paths.get(profile);
        ArrayList<String> list = new ArrayList<>();
        try {
            Files.walk(profilePath)
                    .forEach(path -> {
                        if (Files.isRegularFile(path)) {
                            System.out.println("文件名: " + path.getFileName());
                            System.out.println("文件路径: " + path);
                            list.add(String.valueOf(path));
                        }
                    });
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    //获取文件,修改http请求头
    @Override
    public ResponseEntity<Resource> getFileByPath(String fileName) throws IOException {
        String filePath = profile + "/" + fileName;
        Path path = Paths.get(filePath);
        Resource resource = new FileSystemResource(path);
        if (resource.exists() || resource.isReadable()) {
            String contentType = Files.probeContentType(path);
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                    .contentType(MediaType.parseMediaType(contentType))
                    .body(resource);
        } else {
            return ResponseEntity.status(404).build();
        }
    }
}
相关推荐
Bonne journée5 分钟前
‌在Python中,print(f‘‘)是什么?
java·开发语言·python
2402_8575893625 分钟前
新闻推荐系统:Spring Boot框架详解
java·spring boot·后端
2401_8576226627 分钟前
新闻推荐系统:Spring Boot的可扩展性
java·spring boot·后端
小懒编程日记32 分钟前
【数据结构与算法】B树
java·数据结构·b树·算法
Y_3_742 分钟前
【回溯数独】有效的数独(medium)& 解数独(hard)
java·数据结构·windows·算法·dfs·回溯
RangoLei_Lzs1 小时前
C++模版SFIANE应用踩的一个小坑
java·开发语言·ui
北极无雪1 小时前
Spring源码学习(拓展篇):SpringMVC中的异常处理
java·开发语言·数据库·学习·spring·servlet
VXbishe1 小时前
(附源码)基于springboot的“我来找房”微信小程序的设计与实现-计算机毕设 23157
java·python·微信小程序·node.js·c#·php·课程设计
YONG823_API2 小时前
电商平台数据批量获取自动抓取的实现方法分享(API)
java·大数据·开发语言·数据库·爬虫·网络爬虫
扬子鳄0082 小时前
java注解的处理器
java