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

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),我们来搭建独立的文件服务器

猜你喜欢

转载自blog.csdn.net/qq_41603102/article/details/82453549