今天我們嘗試Spring Boot整合Angular,並決定建立一個非常簡單的Spring Boot微服務,使用Angular作爲前端渲編程語言進行前端頁面渲染.
基礎環境
技術 | 版本 |
---|---|
Java | 1.8+ |
SpringBoot | 1.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:[email protected]">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:[email protected]">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:[email protected]">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:[email protected]">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:[email protected]">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