1、工具类
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Base64;
public class FileDownLoadUtils {
/**
* 下载文件或者在线预览文件,在线预览只支持jpg,png等
*
* @param filename 下载的文件名称
* @param bytes 文件转换的字节码
* @param review 是否在线预览
* @param userAgent 浏览器类型 使用 request.getHeader("User-Agent")获取
* @return
* @throws UnsupportedEncodingException
*/
public static ResponseEntity<Resource> download(String filename, byte[] bytes, boolean review,
String userAgent) throws UnsupportedEncodingException
{
return download(filename, bytes, review ? parseMediaType(filename) : MediaType.APPLICATION_OCTET_STREAM,
userAgent);
}
private static ResponseEntity<Resource> download(String filename, byte[] bytes, MediaType mediaType,
String userAgent) throws UnsupportedEncodingException
{
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
headers.add("charset", "utf-8");
String finalName = URLEncoder.encode(filename, "UTF-8");
if(userAgent != null) {
if(userAgent.toLowerCase().indexOf("firefox") > -1) {
finalName = "=?UTF-8?B?" + new String(Base64.getEncoder().encode(filename.getBytes("UTF-8"))) + "?=";
}
else if(userAgent.toLowerCase().indexOf("safari") > -1) {
finalName = new String(finalName.getBytes("UTF-8"), "ISO8859-1");
}
}
headers.add("Content-Disposition", "filename=\"" + finalName + "\"");
return ((ResponseEntity.BodyBuilder) ResponseEntity.ok().headers(headers)).contentLength((long) bytes.length)
.contentType(mediaType)
.body(new ByteArrayResource(bytes));
}
/**
* 根据文件名称转换文件
* @param fileName
* @return
*/
public static MediaType parseMediaType(String fileName) {
MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
int dot = fileName != null ? fileName.lastIndexOf(".") : -1;
if(dot < 0) {
return mediaType;
}
else {
String suffix = fileName.substring(dot + 1).toUpperCase();
if(suffix.equalsIgnoreCase("GIF")) {
mediaType = MediaType.IMAGE_GIF;
}
else if(suffix.equalsIgnoreCase("PNG")) {
mediaType = MediaType.IMAGE_PNG;
}
else if(!suffix.equalsIgnoreCase("JPG") && !suffix.equalsIgnoreCase("JPEG")) {
if(suffix.equalsIgnoreCase("XML")) {
mediaType = MediaType.APPLICATION_XML;
}
else if(suffix.equalsIgnoreCase("PDF")) {
mediaType = MediaType.APPLICATION_PDF;
}
}
else {
mediaType = MediaType.IMAGE_JPEG;
}
return mediaType;
}
}
}
2、service
import cn.test.authention.service.FileManagerService;
import cn.test.maple.document.util.FileUtil;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import java.io.ByteArrayOutputStream;
@Service
public class FileManagerServiceImpl implements FileManagerService {
private static final Logger log = LoggerFactory.getLogger(FileManagerServiceImpl.class);
@Autowired
private GridFsTemplate gridFsTemplate;
@Autowired
private GridFSBucket gridFSBucket;
private byte[] getFileBytes(String id) {
ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
gridFSBucket.downloadToStream(new ObjectId(id), out);
return out.toByteArray();
}
public ResponseEntity<Resource> downloadFile(String id, boolean review, String userAgent) throws Exception{
Query query = Query.query(Criteria.where("_id").is(id));
// 查询单个文件
GridFSFile gridFSFile = gridFsTemplate.findOne(query);
if(gridFSFile == null) {
log.warn("下载的文件不存在");
throw new RuntimeException("文件不存在");
}
String fileName = gridFSFile.getFilename().replace(",", "");
byte[] bytes = getFileBytes(id);
return FileUtil.download(fileName, bytes, review, userAgent);
}
}
配置类
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
@Configuration
public class MongodbConfig {
@Autowired
private MongoDbFactory mongoDbFactory;
@Bean
public GridFSBucket getGridFSBucket() {
MongoDatabase db = mongoDbFactory.getDb();
return GridFSBuckets.create(db);
}
}
需要引的包
compile 'org.springframework.boot:spring-boot-starter-data-mongodb'