SpringBoot 文件上传/下载

347 阅读1分钟

有啥不懂的或者出错的可以在下面留言。

1. 文件上传

    //上传路径
    String folder = "C:\\code\\springboot-springsecurity\\security-demo\\src\\main\\java\\com\\laojiao\\xxx\\controller";

    @PostMapping
    public String upload(MultipartFile file) throws IOException {

        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getSize());

        //创建本地文件
        File localFile = new File(folder,System.currentTimeMillis()+".txt");
        //把传上来的文件写到本地文件
        file.transferTo(localFile);
        //返回localFile文件路径
        return localFile.getAbsolutePath();
    }

返回是String就是文件所在路径,一般把它放到数据库中。 我在这里用的是单机上传,如果有需要上传到服务器或者fastdfs的只需要把写到本地文件的方式改成获取输入输出流去写文件就行。

2. 文件下载

    @GetMapping("/{id}")
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response){
        try(InputStream inputStream = new FileInputStream(new File(folder,id+".txt"));
            OutputStream outputStream = response.getOutputStream();) {

            //设置内容类型为下载类型
            response.setContentType("application/x-download");
            //设置请求头 和 文件下载名称
            response.addHeader("Content-Disposition","attachment;filename=test.txt");
            //用 common-io 工具 将输入流拷贝到输出流
            IOUtils.copy(inputStream,outputStream);
            outputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

注意IOUtils 是apache的一个工具包,是需要导入common-io依赖包的。或者你手动获取输入输出流转换也可以。

介绍下我的所有文集:

流行框架

SpringCloud

springboot

nginx

redis

底层实现原理:

Java NIO教程

Java reflection 反射详解

Java并发学习笔录

Java Servlet教程

jdbc组件详解

Java NIO教程

Java语言/版本 研究