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{}是关键代码,其他的是我项目的业务逻辑,不用管

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



相关文章
|
6月前
|
Shell 网络安全 开发工具
服务器已经搭建好的项目如何关联至gitee对应仓库并且将服务器的项目代码推送至gitee-优雅草卓伊凡
服务器已经搭建好的项目如何关联至gitee对应仓库并且将服务器的项目代码推送至gitee-优雅草卓伊凡
397 5
|
8月前
|
监控 Java Linux
Apache NiFi项目的编译与部署于CentOS服务器
总而言之,Apache NiFi的编译和部署虽然涉及多个步骤,但这些操作步骤简明扼要,即使是不太熟悉Java或Maven的用户也能跟随指南完成。通过遵循上述步骤,您将能够在CentOS服务器上成功部署Apache NiFi,为您的数据流处理任务建立一个功能强大的平台。
522 16
|
9月前
|
JSON 分布式计算 大数据
springboot项目集成大数据第三方dolphinscheduler调度器
springboot项目集成大数据第三方dolphinscheduler调度器
574 3
|
9月前
|
Java 关系型数据库 数据库连接
Spring Boot项目集成MyBatis Plus操作PostgreSQL全解析
集成 Spring Boot、PostgreSQL 和 MyBatis Plus 的步骤与 MyBatis 类似,只不过在 MyBatis Plus 中提供了更多的便利功能,如自动生成 SQL、分页查询、Wrapper 查询等。
919 3
|
9月前
|
Java 测试技术 Spring
简单学Spring Boot | 博客项目的测试
本内容介绍了基于Spring Boot的博客项目测试实践,重点在于通过测试驱动开发(TDD)优化服务层代码,提升代码质量和功能可靠性。案例详细展示了如何为PostService类编写测试用例、运行测试并根据反馈优化功能代码,包括两次优化过程。通过TDD流程,确保每项功能经过严格验证,增强代码可维护性与系统稳定性。
350 0
|
9月前
|
存储 Java 数据库连接
简单学Spring Boot | 博客项目的三层架构重构
本案例通过采用三层架构(数据访问层、业务逻辑层、表现层)重构项目,解决了集中式开发导致的代码臃肿问题。各层职责清晰,结合依赖注入实现解耦,提升了系统的可维护性、可测试性和可扩展性,为后续接入真实数据库奠定基础。
691 0
|
分布式计算 大数据 Java
springboot项目集成大数据第三方dolphinscheduler调度器 执行/停止任务
springboot项目集成大数据第三方dolphinscheduler调度器 执行/停止任务
231 0
|
6月前
|
弹性计算 运维 安全
阿里云轻量应用服务器与云服务器ECS啥区别?新手帮助教程
阿里云轻量应用服务器适合个人开发者搭建博客、测试环境等低流量场景,操作简单、成本低;ECS适用于企业级高负载业务,功能强大、灵活可扩展。二者在性能、网络、镜像及运维管理上差异显著,用户应根据实际需求选择。
519 10
|
6月前
|
运维 安全 Ubuntu
阿里云渠道商:服务器操作系统怎么选?
阿里云提供丰富操作系统镜像,涵盖Windows与主流Linux发行版。选型需综合技术兼容性、运维成本、安全稳定等因素。推荐Alibaba Cloud Linux、Ubuntu等用于Web与容器场景,Windows Server支撑.NET应用。建议优先选用LTS版本并进行测试验证,通过标准化镜像管理提升部署效率与一致性。

热门文章

最新文章

下一篇
开通oss服务