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

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

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

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

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


前提条件:项目和文件服务器(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

image.gif

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,"上传失败,因为文件是空的");
    }
}

image.gif

注意 :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,"上传失败,因为文件是空的");
    }
}

image.gif

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

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



相关文章
|
29天前
|
安全 云计算
服务器系统资源不足怎么办
服务器系统资源不足怎么办
28 4
|
2月前
|
监控 IDE Java
如何在无需重新启动服务器的情况下在 Spring Boot 上重新加载我的更改?
如何在无需重新启动服务器的情况下在 Spring Boot 上重新加载我的更改?
70 8
|
2月前
|
存储 人工智能 弹性计算
阿里云弹性计算(ECS)提供强大的AI工作负载平台,支持灵活的资源配置与高性能计算,适用于AI训练与推理
阿里云弹性计算(ECS)提供强大的AI工作负载平台,支持灵活的资源配置与高性能计算,适用于AI训练与推理。通过合理优化资源分配、利用自动伸缩及高效数据管理,ECS能显著提升AI系统的性能与效率,降低运营成本,助力科研与企业用户在AI领域取得突破。
60 6
|
2月前
|
Java 应用服务中间件
SpringBoot获取项目文件的绝对路径和相对路径
SpringBoot获取项目文件的绝对路径和相对路径
116 1
SpringBoot获取项目文件的绝对路径和相对路径
|
2月前
|
分布式计算 关系型数据库 MySQL
SpringBoot项目中mysql字段映射使用JSONObject和JSONArray类型
SpringBoot项目中mysql字段映射使用JSONObject和JSONArray类型 图像处理 光通信 分布式计算 算法语言 信息技术 计算机应用
59 8
|
2月前
|
存储 运维 安全
Spring运维之boot项目多环境(yaml 多文件 proerties)及分组管理与开发控制
通过以上措施,可以保证Spring Boot项目的配置管理在专业水准上,并且易于维护和管理,符合搜索引擎收录标准。
47 2
|
2月前
|
前端开发 Java easyexcel
SpringBoot操作Excel实现单文件上传、多文件上传、下载、读取内容等功能
SpringBoot操作Excel实现单文件上传、多文件上传、下载、读取内容等功能
128 8
|
3月前
|
JavaScript 前端开发 Java
解决跨域问题大集合:vue-cli项目 和 java/springboot(6种方式) 两端解决(完美解决)
这篇文章详细介绍了如何在前端Vue项目和后端Spring Boot项目中通过多种方式解决跨域问题。
402 1
解决跨域问题大集合:vue-cli项目 和 java/springboot(6种方式) 两端解决(完美解决)
|
2月前
|
JavaScript 前端开发 Java
SpringBoot项目的html页面使用axios进行get post请求
SpringBoot项目的html页面使用axios进行get post请求
60 2
|
2月前
|
前端开发 Java Spring
SpringBoot项目thymeleaf页面支持词条国际化切换
SpringBoot项目thymeleaf页面支持词条国际化切换
83 2