文件上传和下载

配置文件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>
    <groupId>cn.kgc</groupId>
    <artifactId>sb_upload2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sb_upload2</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </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.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </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>
        <!--文件上传的依赖-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <!--防止扫描不到*Mapper.xml文件-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>cn.kgc.SbUpload2Application</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

 application.yml

spring:
  thymeleaf:
    cache: false
    prefix: classpath:/templates/
  web:
    resources:
      static-locations: classpath:/templates/,classpath:/static/
  datasource: #连接数据库
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/upload0220?characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: root
  servlet:
    multipart:
      max-file-size: 100MB  #设置上传文件最大值
      max-request-size: 100MB  #设置请求最大值


mybatis:
  mapper-locations: classpath:/cn/kgc/zq/mapper/*.xml #设置mapper文件
  type-aliases-package: cn.kgc.zq.pojo  #起别名
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #log日志

实体类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class UserFile {
    //文件ID,文件原始名称,文件新名称,文件后缀,存储路径,文件大小,类型,是否是图片,下载次数,上传时间
    private Integer id;
    private String oldFileName;
    private String newFileName;
    private String ext;
    private String path;
    private String size;
    private String type;
    private String isImg;
    private Integer downcounts;
    private Date uploadTime;
}

Dao层接口

@Mapper
public interface UserFileDao {
    // 获取文件列表
    List<UserFile> findFiles();

    // 存储图片信息
    int save(UserFile userFile);

    // 根据id查找文件详情
    UserFile findFileById(Integer id);

    // 根据id修改下载次数
    int updDownloadCount(Integer id);

    //删除文件
    int deleteFile(Integer id);
}

Service层

Service 接口

public interface UserFileService {
    List<UserFile> findFiles();

    UserFile findFileById(Integer id);

    int save(UserFile userFile);

    int updDownloadCount(Integer id);

    int deleteFile(Integer id);
}

Serviceimpl实现

@Service
public class UserFileServiceImpl implements UserFileService {
    @Resource
    private UserFileDao userFileDao;

    @Override
    public List<UserFile> findFiles() {
        return userFileDao.findFiles();
    }

    @Override
    public UserFile findFileById(Integer id) {
        return userFileDao.findFileById(id);
    }

    @Override
    public int save(UserFile userFile) {
        //如果文件类型的前缀是image,就判断为Yes,否则就是No
        String isImg = userFile.getType().startsWith("image") ? "Yes" : "No";
        userFile.setIsImg(isImg);
        //初次上传,下载次数默认是0
        userFile.setDowncounts(0);
        //设置默认上传时间
        userFile.setUploadTime(new Date());
        return userFileDao.save(userFile);
    }

    @Override
    public int updDownloadCount(Integer id) {
        return userFileDao.updDownloadCount(id);
    }

    @Override
    public int deleteFile(Integer id) {
        return userFileDao.deleteFile(id);
    }
}

mapper  ///SQL

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.kgc.zq.dao.UserFileDao">
    <!--查询所有的文件-->
    <select id="findFiles" resultType="cn.kgc.zq.pojo.UserFile">
        select id,
               oldFileName,
               newFileName,
               ext,
               path,
               size,
               type,
               isImg,
               downcounts,
               uploadTime
        from t_files
    </select>

    <!--上传图片-->
    <insert id="save" parameterType="UserFile">
        insert into t_files(oldFileName, newFileName, ext, path, size, type, isImg, downcounts, uploadTime)
        values (#{oldFileName}, #{newFileName}, #{ext},
                #{path}, #{size}, #{type}, #{isImg},
                #{downcounts}, #{uploadTime})
    </insert>


    <!--  根据id查询单个文件  -->
    <select id="findFileById" resultType="UserFile">
        select id,
               oldFileName,
               newFileName,
               ext,
               path,
               size,
               type,
               isImg,
               downcounts,
               uploadTime
        from t_files
        where id = #{id}
    </select>

    <!--根据id修改下载次数-->
    <update id="updDownloadCount">
        update t_files
        set downcounts=downcounts + 1
        where id = #{id}
    </update>

    <!--根据id删除文件-->
    <delete id="deleteFile">
        delete
        from t_files
        where id = #{id}
    </delete>

</mapper>

 controller 层

@Controller
@RequestMapping("file")
public class FileController {
    @Resource
    private UserFileService userFileService;

    /**
     * 展示所有文件信息
     */
    @GetMapping("look")
    public String findAll(Model model) {
        List<UserFile> list = userFileService.findFiles();
        model.addAttribute("files", list);
        return "index";
    }

    /**
     * 处理上传文件:保存文件信息到数据库
     * 注意参数MultipartFile的变量名必须和表单中的name属性一致,这样才可以接收到文件
     */
    @PostMapping("upload")
    public String upload(MultipartFile aaa) throws IOException {
        // 获取原文件名
        String oldFilename = aaa.getOriginalFilename();

        // 获取原文件的后缀名
        String extension = "." + FilenameUtils.getExtension(oldFilename);

        // 生成新文件名
        String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + extension;

        // 文件大小
        long size = aaa.getSize();

        // 文件类型
        String type = aaa.getContentType();

        // 以下属性放到业务层Service去做
        // 图片ID
        // 是否是图片
        // 下载次数
        // 上传时间

        // 根据日期生成目录
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/files";
        String dateFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dateDirPath = realPath + "/" + dateFormat;

        File dateDir = new File(dateDirPath);
        if (!dateDir.exists()) {
            dateDir.mkdirs();    // mkdirs()可以创建多级目录
        }

        // 处理上传文件
        aaa.transferTo(new File(dateDirPath, newFileName));

        // 将文件信息放入数据库中保存
        // 注意,我们现在在控制层,某一些业务需要放到业务层去做
        UserFile userFile = new UserFile();
        userFile.setOldFileName(oldFilename).setNewFileName(newFileName).setExt(extension).setSize(String.valueOf(size))
                .setType(type).setPath("/files/" + dateFormat);
        //调用保存方法
        userFileService.save(userFile);

        return "redirect:/file/look";    // 文件上传后,重定向到look页面
    }


    /**
     * 文件下载
     */
    @GetMapping("download")
    public void download(String openStyle, Integer id, HttpServletResponse response) throws IOException {
        openStyle = openStyle == null ? "attachment" : openStyle;
        // 根据文件id获取对应的文件信息
        UserFile userFile = userFileService.findFileById(id);
        if ("attachment".equals(openStyle)) {
            // 更新下载次数
            userFileService.updDownloadCount(userFile.getId());
        }
        // 获取文件路径
        System.out.println("File: " + userFile);
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/" + userFile.getPath();
        // 获取文件输入流(把磁盘上的文件通过IO加载到程序(内存)中
        FileInputStream fis = new FileInputStream(new File(realPath, userFile.getNewFileName()));
        // 附件下载
        // 注意:为防止中文乱码,需要使用UTF-8
        response.setHeader("content-disposition", openStyle + ";fileName=" + URLEncoder.encode(userFile.getOldFileName(), "UTF-8"));
        // 获取响应流(找到后需要通过Response发送回给用户
        ServletOutputStream os = response.getOutputStream();
        // 文件拷贝
        IOUtils.copy(fis, os);
        // 关闭流
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(os);
    }


    /**
     * 展示所有文件信息,并以JSON格式返回
     */
    @GetMapping("showAllJSON")
    @ResponseBody
    public List<UserFile> findAllJSON() {
        List<UserFile> files = userFileService.findFiles();
        return files;
    }

    /**
     * 文件删除,包括数据库的文件信息和文件本身
     *
     * @param id 要删除文件的id
     * @return 重定向至用户文件列表首页
     */
    @GetMapping("delete")
    public String delete(Integer id) throws FileNotFoundException {
        // 根据id查询信息
        UserFile userFile = userFileService.findFileById(id);

        // 删除文件:
        // 获取绝对路径
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static" + userFile.getPath();
        // 获得文件
        File file = new File(realPath, userFile.getNewFileName());
        if (file.exists()) {
            file.delete();  // 立即删除
        }

        // 删除数据库中的文件信息
        userFileService.deleteFile(id);
        return "redirect:/file/look";
    }

}

config调用web配置

@Configuration
public class WebConfigurer extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/upload2").setViewName("add");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        super.addViewControllers(registry);
    }
}

HTML页面代码 主页面 和 添加 

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <base th:href="${#request.getContextPath()}+'/'">
    <title>查询页面</title>
    <script th:src="@{/js/jquery-3.6.0.js}"></script>
    <script th:src="@{/js/index.js}"></script>
</head>
<body>
<h1>这是查询页面 <a th:href="@{/upload2}">返回上传页面</a></h1>
<table border="1px">
    <tr>
        <th>ID</th>
        <th>文件原始名称</th>
        <th>文件新名称</th>
        <th>文件后缀</th>
        <th>存储路径</th>
        <th>文件大小</th>
        <th>类型</th>
        <th>是否是图片</th>
        <th>下载次数</th>
        <th>上传时间</th>
        <th>操作</th>
    </tr>
    <tr th:each="file : ${files}">
        <td><span th:text="${file.id}"></span></td>
        <td><span th:text="${file.oldFileName}"></span></td>
        <td><span th:text="${file.newFileName}"></span></td>
        <td><span th:text="${file.ext}"></span></td>
        <td><span th:text="${file.path}"></span></td>
        <td><span th:text="${file.size}"></span></td>
        <td><span th:text="${file.type}"></span></td>
        <td>
            <span th:if="${file.isImg} != 'Yes'" th:text="${file.isImg}"></span>
            <img th:if="${file.isImg} == 'Yes'" style="height: 80px; width: 80px"
                 th:src="${#servletContext.contextPath} + ${file.path} + '/' + ${file.newFileName}" alt="">
        </td>
        <td><span th:id="${file.id}" th:text="${file.downcounts}"></span></td>
        <td><span th:text="${#dates.format(file.uploadTime, 'yyyy-MM-dd HH:mm:ss')}"></span></td>
        <th>
            <a th:href="@{/file/download(id=${file.id})}">下载</a>
            <a th:href="@{/file/download(id=${file.id}, openStyle='inline')}">在线打开</a>
            <a th:href="@{/file/delete(id=${file.id})}">删除</a>
        </th>
    </tr>
</table>

</body>
</html>

---------------------------------------------------------------------------------------------------------------------------------

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <base th:href="${#request.getContextPath()}+'/upload'">
    <title>上传文件</title>
    <script th:src="@{/js/jquery-3.6.0.js}"></script>
    <script th:src="@{/js/add.js}"></script>
</head>
<body>

<h1>这是上传页面 <a th:href="@{/file/look}">去往查询页面</a></h1>
<form th:action="@{/file/upload}" method="post" enctype="multipart/form-data">
    <input type="file" name="aaa"> <input type="submit" value="点击上传">
</form>

</body>
</html>

js 

jQuery-3.60.js

查看js

$(function () {
    // 周期函数
    setInterval(function(){
        $.get("file/showAllJSON", function (res) {
            $.each(res, function (index, file) {
                $('#'+file.id).text(file.downcounts);
            })
        })
    }, 3000);
})

添加

$(function () {
    //表单拦截
    $("form").submit(function () {
        let aaa = $("input[name='aaa']").val().trim();
        if (aaa == "") {
            alert("请选择文件!");
            return false;
        }
    });
})

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值