文件的上传和下载

本文介绍了如何在项目中实现文件的上传和下载功能,包括配置pom.xml引入相关依赖,创建DemoApplication作为应用入口,定义fileController处理文件操作,设计download.html和upload.html作为前端页面,以及设置application.properties文件和编写测试类DemoApplicarionTest。
摘要由CSDN通过智能技术生成

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 https://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.2.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

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

    <dependencies>

        <dependency>
<!--            工具的第三方依赖-->
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
        <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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

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

</project>

DemoApplication

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

fileController

package controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

import static org.springframework.http.HttpStatus.NOT_FOUND;

public class FileController {

    /**
     * 1.浏览器打开访问的URL 路径、即可到达、上传的要页面
     *
     * @return
     */
    @GetMapping("/toUploadPage")
    public String toUpLoadPage() {
        return "upload";
    }

    /**
     * 上传 网页 今内容进行上传到本方法
     *
     * @param files
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadFile")
    public String uploadFile(MultipartFile[] files, Model model) {
        System.out.println("files:" + files.length);
        model.addAttribute("status", "上传成功");
        for (MultipartFile file : files) {
            // 获取上传文件名称(文件名+扩展名)
            String filename = file.getOriginalFilename();
            System.out.println("文件的名称" + filename);
            String dir = "D:/file/";
            File f = new File(dir);

            // 判断文件是否存在
            if (!f.exists()) {
                f.mkdirs();// 不存在创建这个文件
            }

            File uploadfile = new File(dir + filename);
            System.out.println(uploadfile.getPath());
            System.out.println(uploadfile.getName());
            try {
                file.transferTo(uploadfile);
            } catch (IOException e) {
                model.addAttribute("status", "上传失败");

                throw new RuntimeException(e);
            }
        }
        return "upload";
    }


    @GetMapping("/toDownloadPage")
    public String download() {
        return "download";
    }


    /**
     * 文件的下载
     *
     * @param name
     * @return
     */
    @GetMapping("/download")
    public ResponseEntity downLoad(String name) throws RuntimeException {
        String dir = "D:/file/";
        File file = new File(dir + File.separator + name);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", name);


        // 设置文件内容
        headers.setContentType(MediaType.ALL);

        try {
            return new ResponseEntity(FileUtils.readFileToByteArray(file),headers,HttpStatus.OK);
        } catch (IOException e) {
            throw new RuntimeException(e);
//            throw new RuntimeException(e.getMessage().getBytes(), NOT_FOUND);
        }
    }
}

download.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http:www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <table border="1px">
        <tr>
            <td>
                <img src="../static/images/1.jpg" th:src="images/1.jpg" width="168px height="200px">
                <a th:href="@{/downLoad(name='1.jpg')}">点我下载</a>
            </td>
        </tr>
        <tr>
            <td>
                <img src="../static/images/1.jpg" th:src="images/1.jpg" width="168px height="200px">
                <a th:href="@{/downLoad(name='2.jpg')}">点我下载</a>
            </td>
        </tr>
    </table>
</body>
</html>

upload.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>上传文件</title>
</head>
        <!--
            上传 的三大要素
            1.提交方式 post
            2.提交类型 multipart / form-data
            3. 组件类型file:type:file
            -->
<body>
<!--/*@thymesVar id="status" type="ch.qos.logback.classic.AsyncAppender"*/-->
<span  style="color: red" th:text="${status}">上传成功</span>
<form th:action="@{/updaloadFile}" method="post" enctype="multipart/form-data">
    <input type="file" name="files"> <br/>
    <input type="submit" value="上传">

</form>
</body>
</html>

application.properties

# thymeleaf 相关配置
spring.thymeleaf.cache=false
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML
spring.thymeleaf.suffix=.html
spring.thymeleaf.prefix=classpath:/templates/


spring.servlet.multipart.max-file-size=1MB
spring.servlet.multipart.max-request-size=10MB

DemoApplicarionTest

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class DemoApplicationTests {

    @Test
    void contextLoads() {
    }

}

结构
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值