基于SpringBoot和Mybatis企业级简单文件上传下载项目实战(二)

6 篇文章 0 订阅
2 篇文章 0 订阅

继上次的文档:

在文件数据表中添加一条自己定义的文件数据:

测试结果:
在这里插入图片描述
更:FileController

package com.ziye.files.controller;


import com.ziye.files.entity.User;
import com.ziye.files.entity.UserFile;
import com.ziye.files.service.UserFileService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
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;

//    @Value("${upload.dir}")
//    private String uploadPath;

    /**
     * 返回当前用户的所有文件列表---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);
//        //删除文件
        realPath绝对路径
//        String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/files" + userFile.getPath();
//        File file = new File(realPath, userFile.getNewFileName());
//        if(file.exists())
//            file.delete();//立即删除
//
//        //删除数据库中记录
//        userFileService.delete(id);
//        return "redirect:/file/showAll";
//    }
    @GetMapping("/delete")
    public String delete(String id) throws FileNotFoundException {

        //根据id查询信息
        UserFile userFile = userFileService.findById(id);
        //删除文件
//        realPath绝对路径
        String realPath = ResourceUtils.getURL("C:\\ziyefiletest\\").getPath()+ userFile.getPath();
        System.out.println(realPath);
        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 ("attachment".equals(openStyle)) {
//            userFile.setDowncounts(userFile.getDowncounts()+1);
//            userFileService.update(userFile);
//        }
//        //根据文件信息中文件名字 和 文件存储路径获取文件输入流
//        String realpath = ResourceUtils.getURL("classpath:").getPath() + "/static/files" + userFile.getPath();
//        System.out.println(ResourceUtils.getURL("classpath:").getPath());
//        System.out.println(realpath);
//
//
//        //获取文件输入流
//        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(is);
//        IOUtils.closeQuietly(os);
//    }
//      test1
    @GetMapping("/download")
    public void download(String openStyle, String id, HttpServletResponse response) throws IOException {
        //获取打开方式
        openStyle = openStyle == null ? "attachment" : openStyle;
        //获取文件信息
        UserFile userFile = userFileService.findById(id);
        //点击下载链接更新下载次数
        if ("attachment".equals(openStyle)) {
            userFile.setDowncounts(userFile.getDowncounts()+1);
            userFileService.update(userFile);
        }
        //根据文件信息中文件名字 和 文件存储路径获取文件输入流
        String realpath = ResourceUtils.getURL("C:\\ziyefiletest\\").getPath() + userFile.getPath();

        System.out.println(ResourceUtils.getURL("C:\\ziyefiletest").getPath());
        System.out.println(realpath);


        //获取文件输入流
        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(is);
        IOUtils.closeQuietly(os);
    }


    /**
     * 上传文件处理 并保存文件信息到数据库中
     */
//    @PostMapping("/upload")
//    public String upload(MultipartFile inputup, HttpSession session) throws IOException {
//        //获取上传文件用户id
//        User user = (User) session.getAttribute("user");
//        //获取文件原始名称getOriginalFilename
//        String oldFileName = inputup.getOriginalFilename();
//
//        //获取文件后缀
//        String extension = "." + FilenameUtils.getExtension(inputup.getOriginalFilename());
//
//        //生成新的文件名称
//        String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().replace("-", "") + extension;
//
//        //文件大小
//        Long size = inputup.getSize();
//
//        //文件类型
//        String type = inputup.getContentType();
//
//        //处理根据日期生成目录
//        String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/files";
//
//        System.out.println(realPath);
//
//        String dateFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//        String dateDirPath = realPath + "/files/" + dateFormat;
//        System.out.println(dateDirPath);
//        File dateDir = new File(dateDirPath);
//        if (!dateDir.exists()) dateDir.mkdirs();
//
//        //处理文件上传
//        inputup.transferTo(new File(dateDir, newFileName));
//
//        //将文件信息放入数据库保存
//        UserFile userFile = new UserFile();
//        userFile.setOldFileName(oldFileName).
//                setNewFileName(newFileName).
//                setExt(extension)
//                .setSize(String.valueOf(size))
//                .setType(type)
//                .setPath("/files/" + dateFormat).
//                setUserId(user.getId());
//        userFileService.save(userFile);
//
//        return "redirect:/file/showAll";
//    }




//    test1
    @PostMapping("/upload")
    public String upload(MultipartFile inputup, HttpSession session) throws IOException {
        //获取上传文件用户id
        User user = (User) session.getAttribute("user");
        //获取文件原始名称getOriginalFilename
        String oldFileName = inputup.getOriginalFilename();

        //获取文件后缀
        String extension = "." + FilenameUtils.getExtension(inputup.getOriginalFilename());

        //生成新的文件名称
        String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().replace("-", "") + extension;

        //文件大小
        Long size = inputup.getSize();

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

        //处理根据日期生成目录
        String realPath = ResourceUtils.getURL("C:\\ziyefiletest").getPath();

        System.out.println(realPath);

        String dateFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dateDirPath = realPath + dateFormat;
        System.out.println(dateDirPath);
        File dateDir = new File(dateDirPath);
        if (!dateDir.exists()) dateDir.mkdirs();

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

        //将文件信息放入数据库保存
        UserFile userFile = new UserFile();
        userFile.setOldFileName(oldFileName).
                setNewFileName(newFileName).
                setExt(extension)
                .setSize(String.valueOf(size))
                .setType(type)
                .setPath(dateFormat).
                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");
        System.out.println(111111);
        //根据用户id查询有的文件信息
        List<UserFile> userFiles = userFileService.findByUserId(user.getId());
        //存入作用域中
        model.addAttribute("files", userFiles);
        return "showAll";
    }
}

indexcontroller

package com.ziye.files.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class IndexController {
    @GetMapping("/")
    public String toLogin(){
        return "login";
    }

}

usercontroller

package com.ziye.files.controller;

import com.ziye.files.entity.User;
import com.ziye.files.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
@Slf4j
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";
        }
    }

}

结束:在这里插入图片描述

完整代码链接:

链接:https://pan.baidu.com/s/11e5kNz4Fo7QkLQg1y_QNyg 提取码:pysj

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值