程序实现
1、POM文件
<properties>
<java.version>1.8</java.version>
<swagger.version>2.9.2</swagger.version>
<swagger-models.version>1.5.22</swagger-models.version>
<fastjson.version>1.2.76</fastjson.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.9</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>${swagger-models.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2、application.yml
server:
port: 8080
spring:
mvc:
view:
prefix: classpath:/templates/
suffix: .html
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
file:
upload-path: F:/data/
size: 52428800
3 、FileController
package com.study.fileoption.controller;
import com.study.fileoption.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
@RestController
@RequestMapping("/file")
@Api("文件操作")
public class FileController {
@Autowired
private FileService fileService;
@ApiOperation("文件上传")
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) throws Exception {
fileService.fileUpload(file);
return "success";
}
@PostMapping("/download")
@ApiOperation("文件下载")
public String download(@RequestParam("fileName") String fileName, HttpServletResponse response) throws Exception {
fileService.fileDownload(fileName,response);
return "success";
}
@DeleteMapping("/delete")
@ApiOperation("文件删除")
public String delete(@RequestParam("fileName") String fileName) throws Exception {
fileService.fileDelete(fileName);
return "success";
}
}
4、FileService
package com.study.fileoption.service;
import lombok.extern.slf4j.Slf4j;
import cn.hutool.core.io.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Objects;
@Service
@Slf4j
public class FileService {
@Value("${file.upload-path}")
private String filePath;
@Value("${file.size}")
private Long fileSize;
public String fileUpload(MultipartFile file) throws Exception {
try {
if (file.isEmpty()) {
return "文件为空";
}
log.info(file.getOriginalFilename());
if (file.getSize() >fileSize) {
log.error("上传文件规定小于50MB");
throw new Exception("上传文件大于50MB");
}
String fileName = file.getOriginalFilename();
log.info("文件名:" + fileName);
String suffixName = fileName.substring(fileName.lastIndexOf("."));
log.info("文件后缀:" + suffixName);
String path = filePath + fileName;
File dest = new File(path);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
file.transferTo(dest);
return "上传成功";
} catch (Exception e) {
log.error("上传失败: <{}>",e.getMessage(),e);
}
return "上传失败";
}
public void fileDownload(String fileName, HttpServletResponse response) throws Exception {
File file = new File(filePath + fileName);
if (!file.exists()) {
log.error(fileName+" is not exist!");
throw new Exception("文件不存在");
}
try {
downloadFile(response, file);
} catch (Exception e) {
log.error("文件下载异常: <{}>", e.getMessage(), e);
throw new Exception("文件下载失败");
}
}
public String fileDelete(String fileName) throws Exception {
File file = new File(filePath+fileName);
if (!file.exists()) {
log.error("文件不存在");
throw new Exception("文件不存在");
}
try {
if(file.delete()){
return fileName;
}
} catch (Exception e) {
log.error("文件删除异常: <{}>", e.getMessage(), e);
}
log.error("文件删除失败");
throw new Exception("文件删除失败");
}
private void downloadFile(HttpServletResponse response, File file) throws Exception {
if (file.exists()) {
String filename = file.getName();
byte[] buffer = new byte[1024];
try (FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();) {
response.setContentType("application/octet-stream");
response.setHeader("content-type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename, "utf8"));
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer);
i = bis.read(buffer);
}
} catch (Exception e) {
throw new Exception("文件下载失败");
}
}
}
}
5、SwaggerConfig
package com.study.fileoption.config;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
private Boolean swaggerEnable = true;
public static String SWAGGER_TITLE="文件操作";
public static String SWAGGER_VERSION="1.0";
public final static String SWAGGER_URL="http://127.0.0.1:8080";
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(swaggerEnable)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(SWAGGER_TITLE)
.termsOfServiceUrl(SWAGGER_URL)
.version(SWAGGER_VERSION)
.build();
}
}
测试
1、访问 http://localhost:8080/swagger-ui.html 可对上传、下载、删除功能分别测试,均无异常。
|