SpringBoot开发存储服务器实现过程详解

 更新时间:2022年12月05日 11:28:13   作者:EdurtIO  
这篇文章主要为大家介绍了SpringBoot开发存储服务器实现过程详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

正文

今天我们尝试Spring Boot整合Angular,并决定建立一个非常简单的Spring Boot微服务,使用Angular作为前端渲编程语言进行前端页面渲染.

基础环境

技术版本
Java1.8+
SpringBoot1.5.x

创建项目

  • 初始化项目
mvn archetype:generate -DgroupId=com.edurt.sli.sliss -DartifactId=spring-learn-integration-springboot-storage -DarchetypeArtifactId=maven-archetype-quickstart -Dversion=1.0.0 -DinteractiveMode=false
  • 修改pom.xml增加java和springboot的支持
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring-learn-integration-springboot</artifactId>
        <groupId>com.edurt.sli</groupId>
        <version>1.0.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>spring-learn-integration-springboot-storage</artifactId>
    <name>SpringBoot开发存储服务器</name>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${dependency.springboot.version}</version>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${plugin.maven.compiler.version}</version>
                <configuration>
                    <source>${system.java.version}</source>
                    <target>${system.java.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
  • 一个简单的应用类
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edurt.sli.sliss;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * <p> SpringBootStorageIntegration </p>
 * <p> Description : SpringBootStorageIntegration </p>
 * <p> Author : qianmoQ </p>
 * <p> Version : 1.0 </p>
 * <p> Create Time : 2019-06-10 15:53 </p>
 * <p> Author Email: <a href="mailTo:shichengoooo@163.com" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >qianmoQ</a> </p>
 */
@SpringBootApplication
public class SpringBootStorageIntegration {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootStorageIntegration.class, args);
    }
}

添加Rest API接口功能(提供上传服务)

  • 创建一个controller文件夹并在该文件夹下创建UploadController Rest API接口,我们提供一个简单的文件上传接口
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edurt.sli.sliss.controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
 * <p> UploadController </p>
 * <p> Description : UploadController </p>
 * <p> Author : qianmoQ </p>
 * <p> Version : 1.0 </p>
 * <p> Create Time : 2019-06-10 15:55 </p>
 * <p> Author Email: <a href="mailTo:shichengoooo@163.com" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >qianmoQ</a> </p>
 */
@RestController
@RequestMapping(value = "upload")
public class UploadController {
    // 文件上传地址
    private final static String UPLOADED_FOLDER = "/Users/shicheng/Desktop/test/";
    @PostMapping
    public String upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "上传文件不能为空";
        }
        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);
            return "上传文件成功";
        } catch (IOException ioe) {
            return "上传文件失败,失败原因: " + ioe.getMessage();
        }
    }
    @GetMapping
    public Object get() {
        File file = new File(UPLOADED_FOLDER);
        String[] filelist = file.list();
        return filelist;
    }
    @DeleteMapping
    public String delete(@RequestParam(value = "file") String file) {
        File source = new File(UPLOADED_FOLDER + file);
        source.delete();
        return "删除文件" + file + "成功";
    }
}
  • 修改SpringBootAngularIntegration类文件增加以下设置扫描路径,以便扫描Controller
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edurt.sli.sliss;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
/**
 * <p> SpringBootStorageIntegration </p>
 * <p> Description : SpringBootStorageIntegration </p>
 * <p> Author : qianmoQ </p>
 * <p> Version : 1.0 </p>
 * <p> Create Time : 2019-06-10 15:53 </p>
 * <p> Author Email: <a href="mailTo:shichengoooo@163.com" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >qianmoQ</a> </p>
 */
@SpringBootApplication
@ComponentScan(value = {
        "com.edurt.sli.sliss.controller"
})
public class SpringBootStorageIntegration {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootStorageIntegration.class, args);
    }
}

启动服务,测试API接口可用性

在编译器中直接启动SpringBootStorageIntegration类文件即可,或者打包jar启动,打包命令mvn clean package

  • 测试上传文件接口
curl localhost:8080/upload -F "file=@/Users/shicheng/Downloads/qrcode/qrcode_for_ambari.jpg"

返回结果

上传文件成功

  • 测试查询文件接口
curl localhost:8080/upload

返回结果

["qrcode_for_ambari.jpg"]

  • 测试删除接口
curl -X DELETE 'localhost:8080/upload?file=qrcode_for_ambari.jpg'

返回结果

删除文件qrcode_for_ambari.jpg成功

再次查询查看文件是否被删除

curl localhost:8080/upload

返回结果

[]

增加下载文件支持

  • 在controller文件夹下创建DownloadController Rest API接口,我们提供一个文件下载接口
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edurt.sli.sliss.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
 * <p> DownloadController </p>
 * <p> Description : DownloadController </p>
 * <p> Author : qianmoQ </p>
 * <p> Version : 1.0 </p>
 * <p> Create Time : 2019-06-10 16:21 </p>
 * <p> Author Email: <a href="mailTo:shichengoooo@163.com" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >qianmoQ</a> </p>
 */
@RestController
@RequestMapping(value = "download")
public class DownloadController {
    private final static String UPLOADED_FOLDER = "/Users/shicheng/Desktop/test/";
    @GetMapping
    public String download(@RequestParam(value = "file") String file,
                           HttpServletResponse response) {
        if (!file.isEmpty()) {
            File source = new File(UPLOADED_FOLDER + file);
            if (source.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + file);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fileInputStream = null;
                BufferedInputStream bufferedInputStream = null;
                try {
                    fileInputStream = new FileInputStream(source);
                    bufferedInputStream = new BufferedInputStream(fileInputStream);
                    OutputStream outputStream = response.getOutputStream();
                    int i = bufferedInputStream.read(buffer);
                    while (i != -1) {
                        outputStream.write(buffer, 0, i);
                        i = bufferedInputStream.read(buffer);
                    }
                    return "文件下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bufferedInputStream != null) {
                        try {
                            bufferedInputStream.close();
                        } catch (IOException e) {
                            return "文件下载失败,失败原因: " + e.getMessage();
                        }
                    }
                    if (fileInputStream != null) {
                        try {
                            fileInputStream.close();
                        } catch (IOException e) {
                            return "文件下载失败,失败原因: " + e.getMessage();
                        }
                    }
                }
            }
        }
        return "文件下载失败";
    }
}
  • 测试下载文件
curl -o a.jpg 'localhost:8080/download?file=qrcode_for_ambari.jpg'

出现以下进度条

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  148k    0  148k    0     0  11.3M      0 --:--:-- --:--:-- --:--:-- 12.0M

查询是否下载到本地文件夹

ls a.jpg

返回结果

a.jpg

文件大小设置

默认情况下,Spring Boot最大文件上传大小为1MB,您可以通过以下应用程序属性配置值:

  • 配置文件
#http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#common-application-properties
#search multipart
spring.http.multipart.max-file-size=10MB
spring.http.multipart.max-request-size=10MB
  • 代码配置,创建一个config文件夹,并在该文件夹下创建MultipartConfig
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edurt.sli.sliss.config;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.MultipartConfigElement;
/**
 * <p> MultipartConfig </p>
 * <p> Description : MultipartConfig </p>
 * <p> Author : qianmoQ </p>
 * <p> Version : 1.0 </p>
 * <p> Create Time : 2019-06-10 16:34 </p>
 * <p> Author Email: <a href="mailTo:shichengoooo@163.com" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >qianmoQ</a> </p>
 */
@Configuration
public class MultipartConfig {
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize("10240KB"); //KB,MB
        factory.setMaxRequestSize("102400KB");
        return factory.createMultipartConfig();
    }
}

打包文件部署

  • 打包数据
mvn clean package -Dmaven.test.skip=true -X

运行打包后的文件即可

java -jar target/spring-learn-integration-springboot-storage-1.0.0.jar

以上就是SpringBoot开发存储服务器实现过程详解的详细内容,更多关于SpringBoot 存储服务器的资料请关注脚本之家其它相关文章!

相关文章

  • Java中JDBC实现动态查询的实例详解

    Java中JDBC实现动态查询的实例详解

    从多个查询条件中随机选择若干个组合成一个DQL语句进行查询,这一过程叫做动态查询。下面通过实例代码给大家讲解JDBC实现动态查询的方法,需要的朋友参考下吧
    2017-07-07
  • 解决java main函数中的args数组传值问题

    解决java main函数中的args数组传值问题

    这篇文章主要介绍了解决java main函数中的args数组传值问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • Java编写简单计算器的完整实现过程

    Java编写简单计算器的完整实现过程

    这篇文章主要给大家介绍了关于Java编写简单计算器的完整实现过程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12
  • SpringMVC RESTFul及REST架构风格介绍

    SpringMVC RESTFul及REST架构风格介绍

    这篇文章主要为大家介绍了SpringMVC RESTFul及REST架构风格介绍,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-05-05
  • dubbo自定义异常的完整步骤与测试

    dubbo自定义异常的完整步骤与测试

    最近在项目上遇到一个有关dubbo的问题,想着给大家总结下,这篇文章主要给大家介绍了关于dubbo自定义异常的完整步骤与测试的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-06-06
  • SpringBoot中验证用户上传的图片资源的方法

    SpringBoot中验证用户上传的图片资源的方法

    这篇文章主要介绍了在SpringBoot中验证用户上传的图片资源,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-09-09
  • Spring Boot 整合 JWT的方法

    Spring Boot 整合 JWT的方法

    这篇文章主要介绍了Spring Boot 整合 JWT的方法,文中实例代码非常详细,帮助大家更好的理解和学习,感兴趣的朋友可以了解下
    2020-07-07
  • Spring Data Jpa Mysql使用utf8mb4编码的示例代码

    Spring Data Jpa Mysql使用utf8mb4编码的示例代码

    这篇文章主要介绍了Spring Data Jpa Mysql使用utf8mb4编码的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-11-11
  • java如何使用正则表达式限制特殊字符的个数

    java如何使用正则表达式限制特殊字符的个数

    这篇文章主要介绍了java如何使用正则表达式限制特殊字符的个数,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • 使用maven对springboot项目进行瘦身分离jar的多种处理方案

    使用maven对springboot项目进行瘦身分离jar的多种处理方案

    springboot项目打包一般我们都使用它自带的spring-boot-maven-plugin插件,这个插件默认情况下,会把所有的依赖包全部压缩到一个jar里面,今天给大家分享几种方案来如何减小我们的打包文件,需要的朋友可以参考下
    2024-02-02

最新评论