springboot上传下载文件(1)(项目和文件资源放在同一个服务器上)

在单机时代,项目和文件资源放在同一个服务器上

优点:这样做比较便利,项目直接引用就行,实现起来也简单,无需任何复杂技术,保存数据库记录和访问起来也很方便。

缺点:如果只是小项目使用一般也不会有什么问题,但是当项目扩展,文件资源越来越多的话就会存在弊端。一方面,文件和代码耦合在一起,文件越多存放越混乱;另一方面,如果流量比较大,静态文件访问会占据一定的资源,影响正常业务进行,不利于网站快速发展。

本系列文章:

springboot上传下载文件(1)(项目和文件资源放在同一个服务器上)

springboot上传下载文件(2)---搭建独立的文件服务器

springboot上传下载文件(3)--java api 操作HDFS集群+集群配置

springboot上传下载文件(4)--上传下载工具类(已封装)


前提条件:项目和文件服务器(nginx)需一起部署到本地(win10)或者一起部署到服务器上(linux)

1、依赖

没有特别额外要添加的依赖

2、配置

##单个文件最大KB/MB
#spring-boot-starter-parent2.0.0的设置格式
#spring.servlet.multipart.max-file-size=100MB

#spring-boot-starter-parent1.4.3的设置格式
spring.http.multipart.maxFileSize = 100Mb
####

#设置总上传数据大小
#spring-boot-starter-parent2.0.0的设置格式
#spring.servlet.multipart.max-request-size=200MB

#spring-boot-starter-parent1.4.3的设置格式
spring.http.multipart.maxRequestSize=1000Mb

3、接口编写

(1)上传头像:

//上传头像
@PostMapping("/headImg")
public Object uploadHeadimg(@RequestParam("file") MultipartFile file) {
    String username = SecurityContextHolder.getContext().getAuthentication().getName();//获取当前登录用户
    System.out.println( username );
    User user = userService.getUserByUsername(username);
    if (!file.isEmpty()) { //文件不是空文件
        try {
            BufferedOutputStream out = new BufferedOutputStream(
                    //C:\IDEA_mode_project\agriculture\src\main
                    new FileOutputStream(new File(filepath + username + ".jpg")));//保存图片到目录下,建立保存文件的输入流
            out.write(file.getBytes());
            out.flush();
            out.close();
            String filename = filepath + username + ".jpg";
            user.setAvater(filename); //设置头像路径
            userService.saveOrUpdate(user);//修改用户信息
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return new Reponse(false,"上传失败," + e.getMessage());
            //return "上传失败," + e.getMessage();  //文件路径错误
        } catch (IOException e) {
            e.printStackTrace();
            return new Reponse(false,"上传失败," + e.getMessage());
            //return "上传失败," + e.getMessage();  //文件IO错误
        }
        return new Reponse(true,"上传头像成功",user);//返回用户信息
    } else {
        return new Reponse(false,"上传失败,因为文件是空的");
    }
}

注意 :try{}是关键代码,其他的是我项目的业务逻辑,不用管

(2)上传文件

@PostMapping("/docUpload")
public Object docUpload(@RequestParam("title") String title,
                        @RequestParam("description") String description,
                        @RequestParam("file") MultipartFile file ) {
    String author = SecurityContextHolder.getContext().getAuthentication().getName();//获取当前登录用户
    User user = userService.getUserByUsername( author );
    //System.out.println( user );
    String fileName = file.getOriginalFilename().toString();//获取文件名
    //System.out.println( fileName );
    if(fileName.indexOf('?')!=fileName.length()-1)
        fileName=title+fileName.substring(fileName.lastIndexOf("."));

    final SimpleDateFormat sDateFormate = new SimpleDateFormat("yyyymmddHHmmss");  //设置时间格式
    String nowTimeStr = sDateFormate.format(new Date()); // 当前时间
    fileName=fileName.substring(0,fileName.indexOf("."))+nowTimeStr+fileName.substring(fileName.lastIndexOf("."));

    Doc doc = new Doc();
    if (!file.isEmpty()) {
        try {
            BufferedOutputStream out = new BufferedOutputStream(
                    new FileOutputStream(new File(filepath + fileName)));//保存图片到目录下,建立保存文件的输入流
            out.write(file.getBytes());
            out.flush();
            out.close();
            String filename = filepath+fileName;
            Long fileSize = file.getSize();
            System.out.println( file.getSize());

            doc.setTitle( title );
            doc.setAvatar( filename );
            doc.setAuthor( author );
            doc.setAuthor_picture(user.getAvater());
            doc.setUptime( new Date() );
            doc.setDescription( description );
            doc.setFileSize( fileSize );
            docService.saveOrUpdateDoc( doc );

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return new Reponse(false,"上传文件失败," + e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            return new Reponse(false,"上传文件失败," + e.getMessage());
        }
        return new Reponse(true,"上传文件成功",doc);//返回文件信息

    }
    else {
        return new Reponse(false,"上传失败,因为文件是空的");
    }
}

注意 :try{}是关键代码,其他的是我项目的业务逻辑,不用管

写的比较简单。其实不怎么推荐这样做,弊端太大

下一篇:Springboot文件上传下载(2),我们来搭建独立的文件服务器

-->我的springboot系列教程

本篇文章到这里就结束啦,如果喜欢的话,多多支持,欢迎关注!

  • 1
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小牛呼噜噜

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

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

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

打赏作者

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

抵扣说明:

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

余额充值