SpringBoot实现上传下载(二)

这篇写下载。

1.实现思路上一篇的数据库设计中,我们有一个字段始终没有用到fileName,这是用来给Layer对象存储文件名的,以此来完成文件与对象的对应,image.png

预览:image.png

2.Code

View层:首先是加载数据表格异步的时候 我们就获取到了fileName,然后通过获取当前行,来获取当前的fileName文件名。

table.on('tool(test)', function(obj) { 

            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            $ = layui.jquery;
if (layEvent === 'download') { //删除

                var fileName = data.fileName;
             window.location="layer/download?fileName=" fileName;

            }
 });

然后不论是上传下载使用ajax都不推荐(上传下载都属于获取资源请求,a标签等即可实现,而ajax是js异步的封装请求,两者实现目标不一样)

这里使用window.location来实现对文件的请求。

然后是Controller层:

 //下载
    @RequestMapping(value = "Index/layer/download")
    @ResponseBody
    public Map<String,Object> downloadOne(HttpServletRequest req,HttpServletResponse response) throws IOException{
        String fileName = req.getParameter("fileName");// 设置文件名,根据业务需要替换成要下载的文件名
//        String layerId = req.getParameter("layerId");
        String downloadDir = req.getSession().getServletContext().getRealPath("/")  "upload/";
//        String savePath = req.getSession().getServletContext().getRealPath("/")  "download/";
        downloadDir=downloadDir.substring(0,downloadDir.length()-1);
        downloadDir=downloadDir "\\";//下载目录
        String realPath=downloadDir fileName;//
        File file = new File(realPath);//下载目录加文件名拼接成realpath
        if(file.exists()){ //判断文件父目录是否存在
//            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName="   fileName);

            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;

            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("----------file download"   fileName);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }


        return api.returnJson(2,"fail" realPath fileName);
    }

主要就是调IO流,然后下载罢了,拼一下路径和文件名即可

3.效果一览效果.gif

觉得有用就给颗小??吧~

**项目仅供测试学习使用,拒绝任何形式的商业用途,转侵删。项目源码关注公众号Code In Java,回复"SpringBoot上传下载"即可获取。除此之外,还有Java学习图谱,数据结构与算法资料等各种资料都可以在后台获取。**关注公众号:Code In Java资源,项目,面试题一网打尽希望与你成为Java技术的同路人

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个用于创建独立的、基于Spring的应用程序的框架。它简化了Spring应用程序的开发过程,提供了一种快速构建应用程序的方式。 要实现文件的上传和下载功能,可以使用Spring Boot提供的MultipartFile类和Resource类。 1. 实现文件上传: - 在Controller中添加一个POST请求处理方法,使用@RequestParam注解接收上传的文件。 - 使用MultipartFile类的transferTo()方法将文件保存到指定位置。 2. 实现文件下载: - 在Controller中添加一个GET请求处理方法,使用@RequestParam注解接收要下载的文件名。 - 使用Resource类加载文件资源,并返回给客户端。 下面是一个简单的示例代码: ```java import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @Controller public class FileController { private static final String UPLOAD_DIR = "uploads/"; @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return "redirect:/error"; } try { byte[] bytes = file.getBytes(); Path path = Paths.get(UPLOAD_DIR + StringUtils.cleanPath(file.getOriginalFilename())); Files.write(path, bytes); } catch (IOException e) { e.printStackTrace(); } return "redirect:/success"; } @GetMapping("/download") public ResponseEntity<Resource> downloadFile(@RequestParam("filename") String filename) { Path path = Paths.get(UPLOAD_DIR + filename); Resource resource; try { resource = new UrlResource(path.toUri()); } catch (MalformedURLException e) { e.printStackTrace(); return ResponseEntity.notFound().build(); } return ResponseEntity.ok() .contentType(MediaType.APPLICATION_OCTET_STREAM) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") .body(resource); } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值