Java文件中转

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

        前端Vue+element-ui 后端spring

1、前端页面

<!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>
<style>
    #app {
        display: flex; /* 使用 Flexbox 布局 */
        height: 100vh; /* 填充满视口高度 */
        flex-direction: row; /* 子元素水平排列 */
        margin: 0; /* 移除默认的边距 */
        padding: 0; /* 移除默认的内边距 */
    }

    .side-by-side {
        flex: 1; /* 平均分配空间,如果需要不同比例可以设置为具体的数值,如 flex: 2; 对于一个元素,flex: 1; 对于另一个 */
        display: flex; /* 确保内部元素也能使用 Flexbox 布局 */
        flex-direction: column; /* 子元素垂直排列 */
        padding: 10px; /* 可选的内边距 */
        box-sizing: border-box; /* 包括 padding 和 border 在内 */
    }

    .el-card {
        flex: 1; /* 使卡片填充满其父元素的高度 */
        display: flex; /* 确保卡片内部元素也能使用 Flexbox 布局 */
        flex-direction: column; /* 卡片内部元素垂直排列 */
    }

    /* 其他样式保持不变 */
</style>
<body class="gray-bg">
<div id="app" style="height: 100vh">
    <div class="side-by-side">
        <el-card>
            <h1>
                上传文件
            </h1>
            <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-card>
    </div>
    <div class="side-by-side">
        <el-card>
            <h1>
                下载列表
            </h1>
            <div v-for="item in this.fileList">
                <a style="color:cornflowerblue;" @click="getFileByPath(item)">{{item}}</a>
            </div>
        </el-card>
    </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层接口

@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接口

public interface UploadService {
    void UploadFile(MultipartFile file) throws IOException;

    List<String> findFilePath();

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

4、Impl实现类

@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();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值