文件配置

server:
# 文件上传
servlet:
multipart:
enabled: true
file-size-threshold: 2KB
max-file-size: 20MB
max-request-size: 20MB
# 自定义文件配置信息
file:
upload:
# 文件映射路径
fileUrl: /api/file/**
# 文件类型
fileType: xls,xlsx,png,jpg
# 文件真实路径
filePath: C:/Users/long/Desktop/upload-file-city/

文件操作工具类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author 墨龙吟
* @version 1.0.0
* @ClassName FileUtils.java
* @Email 2354713722@qq.com
* @Description TODO
* @createTime 2019年08月27日 - 15:17
*/
public class FileUtils {

private static final Logger log = LoggerFactory.getLogger(FileUtils.class);

/**
* 文件上传
* @param file HTML中form data方式上传的文件,包含二进制数据+文件名称
* @param baseDir 文件保存的基本路径
* @param fileType 文件类型
* @return Map<String, String>
* @throws IOException
*/
public static Map<String, String> UploadFile (MultipartFile file, String baseDir, String fileType) throws IOException {
// 获取后缀
String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".") + 1);
List<String> types = Arrays.asList(fileType.split(","));
List<String> result = types.stream().filter(item -> {
return suffix.equals(item);
}).collect(Collectors.toList());
if (result.size() >= 1) {
// 设置文件路径
String fileDir = UUID.randomUUID() + String.valueOf(System.currentTimeMillis()) + "." + suffix;
// 实例化文件路径
File saveFile = new File(baseDir + File.separator + fileDir);
// 不存在则创建
if (!saveFile.getParentFile().exists()) { saveFile.getParentFile().mkdirs(); }
file.transferTo(saveFile);
log.info("{} 上传成功", file.getOriginalFilename());
Map<String, String> map = new HashMap<>();
map.put("fileName", file.getOriginalFilename());
map.put("fileUrl", fileDir);
return map;
} else {
log.error("{} 类型错误", file.getOriginalFilename());
throw new IOException(file.getOriginalFilename() + "类型错误");
}
}

/**
* 文件下载
* @param filePath 文件存储的路径
* @param fileName 文件名字
* @param fileUrl 文件路径
* @param response HttpServletResponse 返回response
* @throws UnsupportedEncodingException
*/
public static void downloadFile(String filePath, String fileName, String fileUrl, HttpServletResponse response) throws UnsupportedEncodingException {
// 配置文件下载
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
// 下载文件能正常显示中文
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
String file = filePath + fileUrl;
try (
FileInputStream fileInputStream = new FileInputStream(new File(file));
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
) {
byte[] buffer = new byte[1024];
OutputStream outputStream = response.getOutputStream();
int i = bufferedInputStream.read(buffer);
while (i != -1) {
outputStream.write(buffer, 0, i);
i = bufferedInputStream.read(buffer);
}
log.info("{} 文件下载成功", fileName);
} catch (Exception e) {
e.printStackTrace();
log.error("{} 文件下载失败", fileName);
}
}
}

文件路径映射路径

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
* @author 墨龙吟
* @version 1.0.0
* @ClassName FileConfig.java
* @Email 2354713722@qq.com
* @Description TODO
* @createTime 2019年08月27日 - 15:31
*/
@Configuration
public class FileConfig extends WebMvcConfigurationSupport {

@Autowired
private OwnerConfig ownerConfig;

/**
* 配置本地资源映射
* @param registry
*/
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
// 资源映射路径
registry.addResourceHandler(ownerConfig.getFileUrl())
// 本地资源路径
.addResourceLocations("file:" + ownerConfig.getFilePath());
super.addResourceHandlers(registry);
}
}

文件读取配置类

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
* @author 墨龙吟
* @version 1.0.0
* @ClassName OwerConfig.java
* @Email 2354713722@qq.com
* @Description TODO
* @createTime 2019年08月27日 - 15:38
*/
@Setter
@Getter
@Component
@ConfigurationProperties(prefix = "file.upload")
public class OwnerConfig {

private String fileUrl;

private String filePath;

private String fileType;

}

文件Service类

import com.city.cluster.config.OwnerConfig;
import com.city.cluster.entity.FileEntity;
import com.city.cluster.repository.FileRepository;
import com.city.cluster.service.FileService;
import com.city.cluster.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
* @author 墨龙吟
* @version 1.0.0
* @ClassName FileServiceImpl.java
* @Email 2354713722@qq.com
* @Description TODO
* @createTime 2019年08月27日 - 11:21
*/
@Service
public class FileServiceImpl implements FileService {

private static final Logger log = LoggerFactory.getLogger(FileServiceImpl.class);

@Autowired
private OwnerConfig ownerConfig;

@Autowired
private FileRepository fileRepository;

@Override
public FileEntity uploadFile(MultipartFile file) throws IOException {
Map<String, String> uploadFile = FileUtils.UploadFile(file, ownerConfig.getFilePath(), ownerConfig.getFileType());
FileEntity fileEntity = new FileEntity()
.setFileName(uploadFile.get("fileName"))
.setFileUrl(uploadFile.get("fileUrl"))
.setUserId(UUID.randomUUID().toString().replaceAll("-", ""))
.setCreateTime(new Date(System.currentTimeMillis()))
.setUpdateTime(new Date(System.currentTimeMillis()));
return fileRepository.save(fileEntity);
}

@Override
public FileEntity getOneFileById(String fileId) {
return fileRepository.getOne(fileId);
}
}

控制器

import com.city.cluster.config.OwnerConfig;
import com.city.cluster.entity.FileEntity;
import com.city.cluster.service.FileService;
import com.city.cluster.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.UUID;

/**
* @author 墨龙吟
* @version 1.0.0
* @ClassName HomeController.java
* @Email 2354713722@qq.com
* @Description TODO
* @createTime 2019年08月27日 - 09:35
*/
@RestController
@RequestMapping("/api")
public class HomeController {

@Autowired
private FileService fileService;

@Autowired
private OwnerConfig ownerConfig;

/**
* 文件上传
* @param file
* @return
*/
@PostMapping("/home")
public Object home(MultipartFile file) throws IOException {
System.out.println(file.getOriginalFilename());
return fileService.uploadFile(file);
}

/**
* 文件下载
* @param fileId
* @param response
* @throws UnsupportedEncodingException
*/
@GetMapping("/download")
public void downloadFile(@RequestParam("fileId") String fileId, HttpServletResponse response) throws UnsupportedEncodingException {
FileEntity fileEntity = fileService.getOneFileById(fileId);
FileUtils.downloadFile(ownerConfig.getFilePath(), fileEntity.getFileName(), fileEntity.getFileUrl(), response);
}
}

测试

Springboot文件上传和下载_接口

访问资源

Springboot文件上传和下载_java_02

如果对大家有帮助,欢迎关注下个人公众号,谢谢,哈哈

Springboot文件上传和下载_java_03