SpringBoot实现文件上传及下载

目录

项目总代码:

jar包文件上传以及在线浏览图片路径解决问题看这里:https://blog.csdn.net/m0_57249797/article/details/120602022?spm=1001.2014.3001.5501

1、页面开发

1.1、快速构建SpringBoot

可参考:如何快速创建SpringBoot应用

在这里插入图片描述

找不到就搜索
在这里插入图片描述
1.2、写一个简单的登入页面
在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户登入</title>
</head>
<body>
<h1>欢迎访问用户文件管理系统</h1>
<form action="">
    <label for="">
    用户名<input type="text" name="username">
    </label><br/>
    <label for="">
    &nbsp;&nbsp;&nbsp;密码<input type="password" name="password">
    </label><br/>
    <label for="">
        <input type="submit" value="登入">
    </label>
</form>
</body>
</html>

在这里插入图片描述
1.3、展示文件页面
在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户文件列表页面</title>
</head>
<h1>欢迎:xxx</h1>
<h3>文件列表:</h3>
<body>
<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>
        <td>1</td>
        <td>a.txt</td>
        <td>uuid.txt</td>
        <td>.txt</td>
        <td>/files</td>
        <td>1024</td>
        <td>text/plain</td>
        <td></td>
        <td>11</td>
        <td>2020-12-12</td>
        <td>
            <a href="">下载</a>
            <a href="">在线打开</a>
            <a href="">删除</a>
        </td>
    </tr>
</table>
<hr/>
<h3>上传文件</h3>
<form action="">
    <input type="file" name="aaa">
    <input type="submit" value="上传文件">
</form>
</body>
</html>

在这里插入图片描述
1.4、项目需求预览
请添加图片描述

2、mysql库表设计

用户表:

create table t_user
(
	id int(8) null,
	username varchar(80) null,
	password varchar(80) null,
	constraint t_user_pk
		primary key (id)
);

文件表:

create table t_files
(
    id int(8) not null,
    oldFileName varchar(450) null,
    newFileName varchar(250) null,
    ext varchar(20) null,
    path varchar(600) null,
    size varchar(200) null,
    type varchar(120) null,
    isimg varchar(10) null,
    downcounts int(6) null,
    uploadTime datetime null,
    constraint table_name_pk
        primary key (id)
);

3、环境搭建

3.1、新建包和目录:并简单整理
在这里插入图片描述
3.2、添加德鲁伊连接池的依赖

 		<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.19</version>
        </dependency>

3.3、配置Application.properties文件

spring.application.name=springboot-files
server.port=8989
server.servlet.context-path=/springboot-files

spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.web.resources.static-locations=classpath:/templates/,classpath:/static/

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/userfiles?useUnicode=true&character=UTF-8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=198810

mybatis.mapper-locations=classpath:/com/ldx/mapper/*.xml
mybatis.type-aliases-package=com.ldx.entity
mybatis.mapper-locations=classpath:/com/ldx/mapper/*.xml
mybatis.type-aliases-package=com.ldx.entity

3.4、给启动程序添加扫描包注解:@MapperScan(“com.ldx.dao”)

@SpringBootApplication
@MapperScan("com.ldx.dao")
public class SpringbootFilesApplication {

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

}

3.5、启动测试:
在这里插入图片描述

4、登入开发

4.1、给t_user表添加用户信息记录
在这里插入图片描述
4.2、在entity包下写用户对象

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Accessors(chain = true)
public class User {
    private Integer id;
    private String username;
    private String password;
}

4.3、dao包下写查询用户的接口

public interface UserDAO {
    User login(User user);
}

4.4、在resource的mapper下配置用户接口的配置查询文件(UserMapper.xml):

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.ldx.dao.UserDAO">

    <!--login-->
    <select id="login" parameterType="User" resultType="User">
        select id,username,password
        from t_user where username=#{username}
        and password=#{password}
    </select>

</mapper>

4.5、写业务层接口UserService及其实现类:

public interface UserService {
    User login(User user);
}
@Service
@Transactional
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDAO userDAO;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public User login(User user) {
        return userDAO.login(user);
    }
}

4.6、建立controller包并写相关页面跳转控制器:

  • 用户访问主页:
@Controller
public class IndexController {

    @GetMapping("index")
    public String toLogin(){

        return "login";
    }
}
  • 用户登入判断(失败跳回主页):
@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

       //登入方法

    @PostMapping("login")
    public String login(User user, HttpSession session){

        User userDB = userService.login(user);
        if(userDB!=null){
            session.setAttribute("user",userDB);
            return "redirect:/file/showAll";
        }else {
            return "redirect:/index";
        }
    }
}
  • 信息接收:
@Controller
@RequestMapping("file")
public class FileController {

    /*展示所有文件信息*/
    @GetMapping("showAll")
    public String findAll(){
        System.out.println("查询所有进入");
        return "showAll";
    }
}

项目结构:
在这里插入图片描述
4.7、登入测试
访问地址:http://localhost:8989/springboot-files/index
在这里插入图片描述
错误输入会跳回登入页面
正确输入后:
在这里插入图片描述
欢迎xxx改进:
在这里插入图片描述

5、展示用户文件列表

5.1、改进用户表:
给t_files表添加用户id使表关联(不添加外键)

alter table t_files add userid int(8) null;

5.2、在entity包下新建UserFile类

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class UserFile {
    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;
    private Integer userId;//用户关联
}

在dao包下新建与之关联的接口UserFileDAO

public interface UserFileDAO {
    //根据登入用户的ID获取用户的文件列表信息
    List<UserFile> findByUserId(Integer id);
   } 

在mapper目录下建立相关的映射文件UserFileDAOMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.ldx.dao.UserFileDAO">

   <!--根据用户id查询当前用户的文件信息-->
    <select id="findByUserId" parameterType="Integer" resultType="UserFile">
        select id,oldFileName,newFileName,ext,path,size,type,isimg,
        downcounts,uploadTime,userid from t_files where userId=#{id}
    </select>
    
</mapper>    

5.3、开发业务层,在service包下新建UserFileService

public interface UserFileService {
    List<UserFile> findByUserId(Integer id);
    void save(UserFile userFile);
}

同一个包下建立其实现类UserFileServiceImpl

@Service
@Transactional
public class UserFileServiceImpl implements UserFileService{

    @Autowired
    private UserFileDAO userFileDAO;
    /*展示所有文件信息*/
    @GetMapping("showAll")
    public String findAll(HttpSession session, Model model){
        //在登入的session中获取用户的id
        User user = (User)session.getAttribute("user");
        //根据用户的id查询其文件信息
        List<UserFile> userFiles=userFileService.findByUserId(user.getId());
        //存入作用域中
        model.addAttribute("files",userFiles);
        /*System.out.println("查询所有进入");*/
        return "showAll";
    }
}

修改showAll.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户文件列表页面</title>
</head>
<h1>欢迎:<span th:if="${session.user!=null}" th:text="${session.user.username}"></span></h1>
<h3>文件列表:</h3>
<body>
<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,fileStat:${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:text="${file.isImg}"></span></td>
        <td><span th:text="${file.downcounts}"></span></td>
        <td><span th:text="${file.uploadTime}"></span></td>
        <td>
            <a href="">下载</a>
            <a href="">在线打开</a>
            <a href="">删除</a>
        </td>
    </tr>
</table>
<hr/>
<h3>上传文件</h3>
<form th:action="@{/file/upload}" method="post" enctype="multipart/form-data">
    <input type="file" name="aaa">
    <input type="submit" value="上传文件">
</form>
</body>
</html>

6、文件上传实现

6.1、修改文件控制器FileController内容

package com.ldx.controller;


import com.ldx.entity.User;
import com.ldx.entity.UserFile;
import com.ldx.service.UserFileService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("file")
public class FileController {

    @Autowired
    private UserFileService userFileService;
    //上传文件处理,并保持文件信息到数据库中
    @PostMapping("upload")
    public  String upload(MultipartFile aaa,HttpSession session) throws IOException {
        //获取上传文件用户的id
        User user = (User)session.getAttribute("user");
        //获取文件的原始名称
        String oldFileName=aaa.getOriginalFilename();
        //获取文件的后缀
        String extnsion="."+ FilenameUtils.getExtension(aaa.getOriginalFilename());
        //生成新的文件名称
        String newFileName= new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+
                UUID.randomUUID().toString().replace("-","")+extnsion;
        //文件的大小
        long size=aaa.getSize();
        //文件的类型
        String type = aaa.getContentType();
        //处理根据日期生成目录
        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();

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

        //将文件信息放入数据库中
        UserFile userFile = new UserFile();
        userFile.setOldFileName(oldFileName);
        userFile.setNewFileName(newFileName);
        userFile.setExt(extnsion);
        userFile.setSize(String.valueOf(size));
        userFile.setType(type);
        userFile.setPath("/files/"+dateFormat);
        userFile.setUserId(user.getId());
        userFileService.save(userFile);
        return "redirect:/file/showAll";
    }

    /*展示所有文件信息*/
    @GetMapping("showAll")
    public String findAll(HttpSession session, Model model){
        //在登入的session中获取用户的id
        User user = (User)session.getAttribute("user");
        //根据用户的id查询其文件信息
        List<UserFile> userFiles=userFileService.findByUserId(user.getId());
        //存入作用域中
        model.addAttribute("files",userFiles);
        /*System.out.println("查询所有进入");*/
        return "showAll";
    }
}

6.2、修改UserFileDAO接口

public interface UserFileDAO {
    //根据登入用户的ID获取用户的文件列表信息
    List<UserFile> findByUserId(Integer id);

    //保存用户的文件记录
    void save(UserFile userFile);
}

6.3、将信息保存到数据库,修改UserFileDAOMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.ldx.dao.UserFileDAO">

   <!--根据用户id查询当前用户的文件信息-->
    <select id="findByUserId" parameterType="Integer" resultType="UserFile">
        select id,oldFileName,newFileName,ext,path,size,type,isimg,
        downcounts,uploadTime,userid from t_files where userId=#{id}
    </select>

    <insert id="save" parameterType="UserFile" useGeneratedKeys="true" keyProperty="id">
        insert into t_files values(#{id},#{oldFileName},#{newFileName},#{ext},#{path},#{size},#{type},#{isImg},#{downcounts},
        #{uploadTime},#{userId})
    </insert>

</mapper>

6.4、修改UserFileServiceImpl类

@Service
@Transactional
public class UserFileServiceImpl implements UserFileService{

    @Autowired
    private UserFileDAO userFileDAO;

    @Override
    public List<UserFile> findByUserId(Integer id) {
        return userFileDAO.findByUserId(id);
    }

    @Override
    public void save(UserFile userFile) {
        /*userFile.setIsImg(); 是否是图片*/
        userFile.setDowncounts(0);
        userFile.setUploadTime(new Date());
        userFileDAO.save(userFile);
    }
}

6.5、showAll.html修改上传文件表单:

<form th:action="@{/file/upload}" method="post" enctype="multipart/form-data">
    <input type="file" name="aaa">
    <input type="submit" value="上传文件">
</form>

注意:t_user和t_files的主键最好设置为自动递增,不然会出现空指针异常
6.6、测试结果:
在这里插入图片描述
java目录:
在这里插入图片描述
数据库:
在这里插入图片描述

7、判断上传文件是否是图片:

7.1、在UserFileServiceImpl类添加判断图片类型

/*解决方案:当类型中含有image时说明当前类型一定为图片*/
        String isImg = userFile.getType().startsWith("image")?"是":"否";
        userFile.setIsImg(isImg);

在这里插入图片描述

8、最后添加功能删除文件及在线打开,定时更新下载次数

返回目录

完结代码
数据库信息请自行参考上面,这里只提供java代码和配置文件

8.1、项目结构图
在这里插入图片描述
8.2、controller包

FileController:

@Controller
@RequestMapping("file")
public class FileController {

    @Autowired
    private UserFileService userFileService;

    //返回当前用户的所有文件列表---json格式数据
    @GetMapping("findAllJSON")
    @ResponseBody
    public List<UserFile> findAllJSON(HttpSession session, Model model){
        //在登入的session中获取用户的id
        User user = (User)session.getAttribute("user");
        //根据用户的id查询其文件信息
        List<UserFile> userFiles=userFileService.findByUserId(user.getId());
        return userFiles;
    }


    /*删除文件信息*/
    @GetMapping("delete")
    public String delete(String id) throws FileNotFoundException {
        //根据id查询信息
        UserFile userFile = userFileService.findById(id);
        //删除文件
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static" + userFile.getPath();
        File file = new File(realPath, userFile.getNewFileName());
        if(file.exists()){
            file.delete();//立即删除
        }


        //删除数据库中的记录
        userFileService.delete(id);
        return "redirect:/file/showAll";
    }
    /*文件下载*/
    @GetMapping("download")
    public void download(String openStyle,String id, HttpServletResponse response) throws IOException {
        //获取打开方式
        openStyle=openStyle==null?"attachment":openStyle;
        //获取文件信息
        UserFile userFile=userFileService.findById(id);
        //点击下载链接更新下载次数
        if(openStyle.equals("attachment")){
            userFile.setDowncounts(userFile.getDowncounts()+1);
            userFileService.update(userFile);
        }
        //根据文件信息中文件名字 和 文件存储路径获取文件输入流
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static" + userFile.getPath();
        //获取文件输入流
        FileInputStream is = new FileInputStream(new File(realPath, userFile.getNewFileName()));
        //附件下载
        response.setHeader("content-disposition",openStyle+";fileName="+ URLEncoder.encode(userFile.getOldFileName(),"UTF-8"));
        //获取响应输出流
        ServletOutputStream os=response.getOutputStream();
        //文件拷贝
        IOUtils.copy(is,os);
        IOUtils.closeQuietly(os);
    }

    //上传文件处理,并保持文件信息到数据库中
    @PostMapping("upload")
    public  String upload(MultipartFile aaa,HttpSession session) throws IOException {
        //获取上传文件用户的id
        User user = (User)session.getAttribute("user");
        //获取文件的原始名称
        String oldFileName=aaa.getOriginalFilename();
        //获取文件的后缀
        String extnsion="."+ FilenameUtils.getExtension(aaa.getOriginalFilename());
        //生成新的文件名称
        String newFileName= new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+
                UUID.randomUUID().toString().replace("-","")+extnsion;
        //文件的大小
        long size=aaa.getSize();
        //文件的类型
        String type = aaa.getContentType();
        //处理根据日期生成目录
        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();

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

        //将文件信息放入数据库中
        UserFile userFile = new UserFile();
        userFile.setOldFileName(oldFileName);
        userFile.setNewFileName(newFileName);
        userFile.setExt(extnsion);
        userFile.setSize(String.valueOf(size));
        userFile.setType(type);
        userFile.setPath("/files/"+dateFormat);
        userFile.setUserId(user.getId());
        userFileService.save(userFile);
        return "redirect:/file/showAll";
    }

    /*展示所有文件信息*/
    @GetMapping("showAll")
    public String findAll(HttpSession session, Model model){
        //在登入的session中获取用户的id
        User user = (User)session.getAttribute("user");
        //根据用户的id查询其文件信息
        List<UserFile> userFiles=userFileService.findByUserId(user.getId());
        //存入作用域中
        model.addAttribute("files",userFiles);
        /*System.out.println("查询所有进入");*/
        return "showAll";
    }
}

IndexController:

@Controller
public class IndexController {

    @GetMapping("index")
    public String toLogin(){

        return "login";
    }
}

UserController:

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

       //登入方法

    @PostMapping("login")
    public String login(User user, HttpSession session){

        User userDB = userService.login(user);
        if(userDB!=null){
            session.setAttribute("user",userDB);
            return "redirect:/file/showAll";
        }else {
            return "redirect:/index";
        }
    }
}

8.3、dao包

UserDAO:

public interface UserDAO {
    User login(User user);
}

UserFileDAO:

public interface UserFileDAO {

    //根据登入用户的ID获取用户的文件列表信息
    List<UserFile> findByUserId(Integer id);

    //保存用户的文件记录
    void save(UserFile userFile);

    //根据文件id获取文件信息
    UserFile findById(String id);

    //根据id更新下载次数
    void update(UserFile userFile);

    //根据id删除记录
    void delete(String id);

}

8.4、entity包

User:

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Accessors(chain = true)
public class User {
    private Integer id;
    private String username;
    private String password;
}

UserFile:

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class UserFile {
    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;
    private Integer userId;//用户关联
}

8.5、service包:
UserFileService:

public interface UserFileService {
    List<UserFile> findByUserId(Integer id);
    void save(UserFile userFile);

    UserFile findById(String id);

    void update(UserFile userFile);

    void delete(String id);
}

UserFileServiceImpl:

@Service
@Transactional
public class UserFileServiceImpl implements UserFileService{

    @Autowired
    private UserFileDAO userFileDAO;

    @Override
    public List<UserFile> findByUserId(Integer id) {
        return userFileDAO.findByUserId(id);
    }

    @Override
    public void save(UserFile userFile) {
        /*userFile.setIsImg(); 是否是图片*/
        /*解决方案:当类型中含有image时说明当前类型一定为图片*/
        String isImg = userFile.getType().startsWith("image")?"是":"否";
        userFile.setIsImg(isImg);

        userFile.setDowncounts(0);
        userFile.setUploadTime(new Date());
        userFileDAO.save(userFile);
    }

    @Override
    public UserFile findById(String id) {
        return userFileDAO.findById(id);
    }

    @Override
    public void update(UserFile userFile) {
        userFileDAO.update(userFile);
    }

    @Override
    public void delete(String id) {
        userFileDAO.delete(id);
    }
}

UserService:

public interface UserService {
    User login(User user);
}

UserServiceImpl:

@Service
@Transactional
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDAO userDAO;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public User login(User user) {
        return userDAO.login(user);
    }
}

8.6、启动类:

SpringbootFilesApplication:

@SpringBootApplication
@MapperScan("com.ldx.dao")
public class SpringbootFilesApplication {

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

}

8.7、位于resource下的配置信息和静态资源

Mapper映射文件:

UserFileDAOMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.ldx.dao.UserFileDAO">

   <!--根据用户id查询当前用户的文件信息-->
    <select id="findByUserId" parameterType="Integer" resultType="UserFile">
        select id,oldFileName,newFileName,ext,path,size,type,isimg,
        downcounts,uploadTime,userid from t_files where userid=#{id}
    </select>

    <!--保存文件信息-->
    <insert id="save" parameterType="UserFile" useGeneratedKeys="true" keyProperty="id">
        insert into t_files values(#{id},#{oldFileName},#{newFileName},#{ext},#{path},#{size},#{type},#{isImg},#{downcounts},
        #{uploadTime},#{userId})
    </insert>
    
    <!--根据id获取文件信息-->
    <select id="findById" parameterType="String" resultType="UserFile">
        select id,oldFileName,newFileName,ext,path,size,type,isimg,
        downcounts,uploadTime,userid from t_files where id=#{id}
    </select>

    <!--更新下载次数-->
    <update id="update" parameterType="UserFile">
        update t_files set downcounts=#{downcounts} where id=#{id}
    </update>

    <!--根据id删除记录-->
    <delete id="delete" parameterType="String">
        delete from t_files where id=#{id}
    </delete>
</mapper>

UserMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.ldx.dao.UserDAO">

    <!--login-->
    <select id="login" parameterType="User" resultType="User">
        select id,username,password
        from t_user where username=#{username}
        and password=#{password}
    </select>

</mapper>

templates包下的文件:

login.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户登入</title>
</head>
<body>
<h1>欢迎访问用户文件管理系统</h1>
<form th:action="@{/user/login}" method="post">
    <label for="/files">
    用户名<input type="text" name="username">
    </label><br/>
    <label for="">
    &nbsp;&nbsp;&nbsp;密码<input type="password" name="password">
    </label><br/>
    <label for="">
        <input type="submit" value="登入">
    </label>
</form>
</body>
</html>

showAll.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户文件列表页面</title>
    <script th:src="@{/js/jquery.min.js}"></script>
    <script>
        $(function () {

            let time;
            $("#start").on("click",function () {
               /*开启定时更新*/
                time=setInterval(function () {
                    $.get("[[@{/file/findAllJSON}]]",function (res) {
                        //遍历
                        $.each(res,function (index,element) {
                            $("#"+element.id).text(element.downcounts);
                        })
                    })
                },3000)
            })

            $("#stop").on("click",function () {
                /*关闭定时更新*/
                clearInterval(time);
            })
        })
    </script>
</head>
<h1>欢迎:<span th:if="${session.user!=null}" th:text="${session.user.username}"></span></h1>
<h3>文件列表:</h3>
<button id="start">开启定时更新</button>
<button id="stop">结束定时更新</button>
<body>
<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,fileStat:${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>
            <img th:if="${file.isImg}==''" style="width: 100px;height: 100px;" th:src="${#servletContext.contextPath}+${file.path}+'/'+${file.newFileName}" alt="">
            <span th:if="${file.isImg}!=''" th:text="${file.isImg}"></span>
        </td>
        <td th:id="${file.id}"><span th:text="${file.downcounts}"></span></td>
        <td><span th:text="${#dates.format(file.uploadTime,'yyyy-MM-dd HH:mm:ss')}"></span></td>
        <td>
            <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>
        </td>
    </tr>
</table>
<hr/>
<h3>上传文件</h3>
<form th:action="@{/file/upload}" method="post" enctype="multipart/form-data">
    <input type="file" name="aaa">
    <input type="submit" value="上传文件">
</form>
</body>
</html>

总配置(直接位于resource下)

application.properties:

spring.application.name=springboot-files
server.port=8989
server.servlet.context-path=/springboot-files

spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.web.resources.static-locations=classpath:/templates/,classpath:/static/

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/userfiles?useUnicode=true&character=UTF-8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=198810

mybatis.mapper-locations=classpath:/com/ldx/mapper/*.xml
mybatis.type-aliases-package=com.ldx.entity

logging.level.root=info
logging.level.com.ldx.dao=debug

运行结果:
在这里插入图片描述

  • 15
    点赞
  • 76
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CharmDeer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值