Java如何进行文件的上传和下载

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>file</title>
</head>
<body>
<h1>文件列表</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.getId()}"></span></td>
<td><span th:text="${file.getOldFileName()}"></span></td>
<td><span th:text="${file.getNewFileName()}"></span></td>
<td><span th:text="${file.getExt()}"></span></td>
<td><span th:text="${file.getPath()}"></span></td>
<td><span th:text="${file.getSize()}"></span></td>
<td><span th:text="${file.getType()}"></span></td>
<td><span th:text="${file.getIsimg()}"></span></td>
<td><span th:text="${file.getDowncOunts()}"></span></td>
<td><span th:text="${file.getUploadTime()}"></span></td>
<td>
<a th:href="@{/downLoad(id=${file.getId()})}">下载</a>
<a th:href="@{/downLoad(id=${file.getId()},openStyle='inline')}">在线打开</a>
<a th:href="@{/delete(id=${file.getId()})}">删除</a>
</td>
</tr>
</table>
<h3>上传文件</h3>
<form th:action="@{/upload}" method="post" enctype="multipart/form-data">
<input type="file" name="multipartFile">
<input type="submit" value="上传文件">
</form>
</body>
</html>

上面部分为演示前端代码,查询的sql语句以及添加的sql等已省略仅展示重点代码

文件的上传功能


@RequestMapping("/upload")

public String upload(MultipartFile multipartFile) throws IOException {
        //获取文件的名称
        String oldName = multipartFile.getOriginalFilename();

        //获取文件的后缀
        String extension = FilenameUtils.getExtension(multipartFile.getOriginalFilename());

        //生成新的文件名称
        String newName = "11111"+"."+extension;

        //文件的大小
        String size = String.valueOf(multipartFile.getSize());

        //文件的类型
        String contentType = multipartFile.getContentType();

        //处理文件上传,首先获取文件的路径
        String realPath = ResourceUtils.getURL("classpath:").getPath()+"/static/files";

        System.err.println(realPath);

        //生成存储目录
        String datePath = realPath + "/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date());

        //判断文件是否存在,如果不存在就创建文件
        File path = new File(datePath);
        if (!path.exists())
            path.mkdirs();

        //处理文件上传
        multipartFile.transferTo(new File(path, oldName));

        //将文件信息放入到数据库中进行保存
        TFile tFile = new TFile();
        tFile.setUserName("李四");
        tFile.setOldFileName(oldName);
        tFile.setNewFileName(newName);
        tFile.setExt(extension);
        tFile.setSize(size);
        tFile.setType(contentType);
        tFile.setPath(datePath);
        tFile.setUploadTime(new Date());
        int i = fileService.insertTFile(tFile);
    //通过springboot自带的引擎模板进行重定向
return "redirect:/select"; }

 

@RequestMapping("/select")
    public String selectAll(HttpSession session, Model model){
        List<TFile> tFiles = fileService.selectOne();
        model.addAttribute("files",tFiles);
        return "file";
    }

查询数据库通过引擎模板进行跳转到前端页面,同时也把查询的数据展示在前端页面

文件的下载和在线打开


/**
* 文件的下载和在线打开
*注意:如果是在线打开,只支持浏览器支持的格式要想实现在线打开只需要把
* response.setHeader("content-disposition", "attachment;fileName="+ URLEncoder.encode(tFile.getOldFileName(), "utf-8"));
* 改成
* response.setHeader("content-disposition", "inline;fileName="+ URLEncoder.encode(tFile.getOldFileName(), "utf-8"));
* @param openStyle
* @param id
* @param response
* @throws IOException
*/
@RequestMapping("/downLoad")
public void downLoad(String openStyle,Integer id, HttpServletResponse response) throws IOException {
//获取打开方式(openStyle是否为空,如果为空则openStyle.equals(attachment),如果不为空,则openStyle=他自己)
openStyle = openStyle == null? "attachment":openStyle;
long fileId = id;
//获取文件信息
TFile tFile = fileService.selectTFileById(fileId);
//根据文件信息中文件名字 和 文件存储路径获取文件输入流
String path = tFile.getPath();
//获取文件输入流
FileInputStream is = new FileInputStream(new File(path, tFile.getOldFileName()));
//附件下载
response.setHeader("content-disposition", openStyle+";fileName="+ URLEncoder.encode(tFile.getOldFileName(), "utf-8"));
//获取响应输出流
ServletOutputStream os = response.getOutputStream();
//文件拷贝
IOUtils.copy(is, os);
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}



所需依赖

     <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

 

posted @ 2022-03-18 14:25  小样儿i  阅读(258)  评论(0)    收藏  举报