提交 ff207da6 编写于 作者: sq3536's avatar sq3536

网盘

上级 65d1bb03
...@@ -3,7 +3,9 @@ package cn.ibizlab.core.disk.extensions.service; ...@@ -3,7 +3,9 @@ package cn.ibizlab.core.disk.extensions.service;
import cn.ibizlab.core.disk.domain.SDFile; import cn.ibizlab.core.disk.domain.SDFile;
import cn.ibizlab.core.disk.service.ISDFileService; import cn.ibizlab.core.disk.service.ISDFileService;
import cn.ibizlab.util.domain.FileItem; import cn.ibizlab.util.domain.FileItem;
import cn.ibizlab.util.errors.BadRequestAlertException;
import cn.ibizlab.util.errors.InternalServerErrorException; import cn.ibizlab.util.errors.InternalServerErrorException;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
...@@ -17,8 +19,11 @@ import org.springframework.web.multipart.MultipartFile; ...@@ -17,8 +19,11 @@ import org.springframework.web.multipart.MultipartFile;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.sql.Wrapper;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List;
@Primary @Primary
@Slf4j @Slf4j
...@@ -33,36 +38,54 @@ public class DiskCoreService { ...@@ -33,36 +38,54 @@ public class DiskCoreService {
@Autowired @Autowired
private ISDFileService sdFileService; private ISDFileService sdFileService;
public FileItem saveFile(MultipartFile multipartFile) { @Autowired
private FileCoreService fileCoreService;
public FileItem saveFile(MultipartFile multipartFile) {
return saveFile("",multipartFile); return saveFile("",multipartFile);
} }
public FileItem saveFile(String folder,MultipartFile multipartFile) { public FileItem saveFile(String folder,MultipartFile multipartFile) {
return saveFile(folder,"",multipartFile); return saveFile(folder,"",multipartFile);
} }
public FileItem saveFile(String folder,String fileId,MultipartFile multipartFile) { public FileItem saveFile(String folder,String fileId,MultipartFile multipartFile) {
return saveFile(folder,"","","",multipartFile);
}
public FileItem saveFile(String folder,String fileId,String ownerType,String ownerId,MultipartFile multipartFile) {
SDFile sdFile = new SDFile(); SDFile sdFile = new SDFile();
if(!StringUtils.isEmpty(fileId)) if(!StringUtils.isEmpty(fileId))
sdFile.setId(fileId); sdFile.setId(fileId);
if(!StringUtils.isEmpty(folder)) if(!StringUtils.isEmpty(folder))
sdFile.setId(folder); sdFile.setId(folder);
return saveFile(sdFile,multipartFile); if(!StringUtils.isEmpty(ownerId))
sdFile.setOwnerId(ownerId);
if(!StringUtils.isEmpty(ownerType))
sdFile.setOwnerType(ownerType);
String fileName = multipartFile.getOriginalFilename();
sdFile.setName(fileName);
int size = (int)multipartFile.getSize();
sdFile.setFileSize(size);
try {
return saveFile(sdFile,multipartFile.getBytes());
} catch (IOException e) {
throw new InternalServerErrorException("文件上传失败");
}
} }
public FileItem saveFile(SDFile sdFile,MultipartFile multipartFile) { public FileItem saveFile(SDFile sdFile,byte[] multipartFile) {
FileItem item=null; FileItem item=null;
try { try {
String fileName = multipartFile.getOriginalFilename(); String fileName = sdFile.getName();
sdFile.setName(fileName);
String extension="."+getExtensionName(fileName); String extension="."+getExtensionName(fileName);
sdFile.setExtension(extension); sdFile.setExtension(extension);
String digestCode = DigestUtils.md5DigestAsHex(multipartFile.getInputStream()); String digestCode = DigestUtils.md5DigestAsHex(multipartFile);
sdFile.setDigestCode(digestCode); sdFile.setDigestCode(digestCode);
String fileId = sdFile.getId(); String fileId = sdFile.getId();
if(StringUtils.isEmpty(fileId)) if(StringUtils.isEmpty(fileId))
{ {
fileId = simpleDateFormat.format(new Date()).concat("-").concat(digestCode); fileId = simpleDateFormat.format(new Date()).concat("_").concat(digestCode);
sdFile.setId(fileId); sdFile.setId(fileId);
} }
String folder = sdFile.getFolder(); String folder = sdFile.getFolder();
...@@ -73,19 +96,18 @@ public class DiskCoreService { ...@@ -73,19 +96,18 @@ public class DiskCoreService {
} }
String filePath = sdFile.getFilePath(); String filePath = sdFile.getFilePath();
if(StringUtils.isEmpty(filePath)) { if(StringUtils.isEmpty(filePath)) {
filePath = folder.concat(File.separator).concat(fileId).concat(File.separator).concat(fileName); filePath = folder.concat(File.separator).concat(fileId.replace("_",File.separator)).concat(File.separator).concat(fileName);
sdFile.setFilePath(filePath); sdFile.setFilePath(filePath);
} }
int size = (int)multipartFile.getSize();
sdFile.setFileSize(size);
String fileFullPath = this.fileRoot.concat(filePath); String fileFullPath = this.fileRoot.concat(filePath);
fileFullPath = fileFullPath.replace("\\",File.separator).replace("/",File.separator); fileFullPath = fileFullPath.replace("\\",File.separator).replace("/",File.separator);
File file = new File(fileFullPath); File file = new File(fileFullPath);
File parent = new File(file.getParent()); File parent = new File(file.getParent());
if(!parent.exists()) if(!parent.exists())
parent.mkdirs(); parent.mkdirs();
FileCopyUtils.copy(multipartFile.getInputStream(),Files.newOutputStream(file.toPath())); FileCopyUtils.copy(multipartFile,Files.newOutputStream(file.toPath()));
item=new FileItem(fileId,fileName,fileId,fileName,size,extension); item=new FileItem(fileId,fileName,fileId,fileName,sdFile.getFileSize(),extension,fileCoreService.getAuthCode(fileId));
sdFileService.save(sdFile); sdFileService.save(sdFile);
} catch (IOException e) { } catch (IOException e) {
throw new InternalServerErrorException("文件上传失败"); throw new InternalServerErrorException("文件上传失败");
...@@ -98,14 +120,23 @@ public class DiskCoreService { ...@@ -98,14 +120,23 @@ public class DiskCoreService {
} }
public File getFile(String folder,String fileId) { public File getFile(String folder,String fileId) {
return getFile("",fileId,"");
}
public File getFile(String folder,String fileId,String authcode) {
if(StringUtils.isEmpty(folder)) if(StringUtils.isEmpty(folder))
folder = "ibizutil"; folder = "ibizutil";
String dirpath = this.fileRoot.concat(folder).concat(File.separator).concat(fileId); if(folder.toUpperCase().startsWith("ibizutil")) {
File parent = new File(dirpath); String dirpath = this.fileRoot.concat(folder).concat(File.separator).concat(fileId.replace("_", File.separator));
if (parent.exists() && parent.isDirectory() && parent.listFiles().length > 0) { File parent = new File(dirpath);
return parent.listFiles()[0]; if (parent.exists() && parent.isDirectory() && parent.listFiles().length > 0) {
return parent.listFiles()[0];
}
} }
return getFile(sdFileService.get(fileId)); else if (StringUtils.isEmpty(authcode)||(authcode.equals(fileCoreService.getAuthCode(fileId)))) {
throw new BadRequestAlertException("没有权限下载","SDFile","");
}
SDFile sdFile = sdFileService.get(fileId);
return getFile(sdFile);
} }
public File getFile(SDFile sdFile) { public File getFile(SDFile sdFile) {
...@@ -119,6 +150,29 @@ public class DiskCoreService { ...@@ -119,6 +150,29 @@ public class DiskCoreService {
throw new InternalServerErrorException("文件未找到"); throw new InternalServerErrorException("文件未找到");
} }
public List<FileItem> getFileList(String ownerType,String ownerId)
{
List<FileItem> fileItems = new ArrayList<>();
sdFileService.list(Wrappers.<SDFile>lambdaQuery().eq(SDFile::getOwnerType,ownerType).eq(SDFile::getOwnerId,ownerId).orderByAsc(SDFile::getCreatedate)).forEach(item -> {
fileItems.add(new FileItem(item.getId(),item.getName(),item.getId(),item.getName(),item.getFileSize(),item.getExtension(),fileCoreService.getAuthCode(item.getId())));
});
return fileItems;
}
public void saveFileList(String ownerType,String ownerId,List<FileItem> fileItems)
{
List<SDFile> sdFiles = new ArrayList<>();
fileItems.forEach(item -> {
SDFile sdFile = new SDFile();
sdFile.setId(item.getId());
sdFile.setOwnerType(ownerType);
sdFile.setOwnerId(ownerId);
sdFiles.add(sdFile);
});
sdFileService.updateBatch(sdFiles);
}
/** /**
* 获取文件扩展名 * 获取文件扩展名
* @param fileName * @param fileName
......
package cn.ibizlab.core.disk.extensions.service;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
@Primary
@Slf4j
@Service
public class FileCoreService {
@Cacheable( value="file",key = "'authcode:'+#p0")
public String getAuthCode(String fileId)
{
return IdWorker.getIdStr();
}
}
...@@ -3,17 +3,22 @@ package cn.ibizlab.api.rest.extensions; ...@@ -3,17 +3,22 @@ package cn.ibizlab.api.rest.extensions;
import cn.ibizlab.core.disk.extensions.service.DiskCoreService; import cn.ibizlab.core.disk.extensions.service.DiskCoreService;
import cn.ibizlab.util.domain.FileItem; import cn.ibizlab.util.domain.FileItem;
import cn.ibizlab.util.service.FileService; import cn.ibizlab.util.errors.BadRequestAlertException;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.*; import java.io.*;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.List;
@Slf4j @Slf4j
@RestController @RestController
...@@ -38,6 +43,12 @@ public class DiskCoreResource ...@@ -38,6 +43,12 @@ public class DiskCoreResource
type.put(".tif", "image/tiff"); type.put(".tif", "image/tiff");
type.put(".tiff", "image/tiff"); type.put(".tiff", "image/tiff");
type.put(".png", "image/png"); type.put(".png", "image/png");
type.put(".doc","application/msword");
type.put(".docx","application/msword");
type.put(".xls","application/vnd.ms-excel");
type.put(".xlsx","application/vnd.ms-excel");
type.put(".wps","application/vnd.ms-works");
type.put(".txt","text/plain");
} }
if(type.containsKey(ext.toLowerCase())) if(type.containsKey(ext.toLowerCase()))
...@@ -47,38 +58,38 @@ public class DiskCoreResource ...@@ -47,38 +58,38 @@ public class DiskCoreResource
} }
@PostMapping(value = "{folder}/upload") @Value("${ibiz.filePath:/app/file/}")
public ResponseEntity<FileItem> upload(@PathVariable("folder") String folder,@RequestParam("file") MultipartFile multipartFile){ private String fileRoot;
return ResponseEntity.ok().body(diskCoreService.saveFile(folder,multipartFile));
}
@PostMapping(value = "{folder}/upload/{id}")
public ResponseEntity<FileItem> updatefile(@PathVariable("folder") String folder,@PathVariable("id") String id,@RequestParam("file") MultipartFile multipartFile){
return ResponseEntity.ok().body(diskCoreService.saveFile(folder,id,multipartFile));
}
@GetMapping(value = "{folder}/download/{id}") @PostMapping(value = {"net-disk/upload/{folder}/{id}/{name}.{ext}","{folder}/upload/{id}","{folder}/upload"})
@ResponseStatus(HttpStatus.OK) public ResponseEntity<FileItem> updatefile(@PathVariable("folder") String folder, @PathVariable(value = "id",required = false) String id,
public void download(@PathVariable("folder") String folder, @PathVariable("id") String id, HttpServletResponse response){ @PathVariable(value = "name",required = false) String name, @PathVariable(value = "ext",required = false) String ext,
File file = diskCoreService.getFile(folder,id); @RequestParam(value = "ownertype",required = false) String ownertype, @RequestParam(value = "ownerid",required = false) String ownerid,
response.setHeader("Content-Disposition", "attachment;filename="+getFileName(file.getName())); @RequestParam("file") MultipartFile multipartFile){
this.sendRespose(response, file); return ResponseEntity.ok().body(diskCoreService.saveFile(folder,id,ownertype,ownerid,multipartFile));
} }
@GetMapping(value = "net-disk/download/{folder}/{id}/{name}.{ext}")
@GetMapping(value = {"net-disk/download/{folder}/{id}/{name}.{ext}","{folder}/download/{id}"})
@ResponseStatus(HttpStatus.OK) @ResponseStatus(HttpStatus.OK)
public void download(@PathVariable("folder") String folder, @PathVariable("id") String id, public void download(@PathVariable("folder") String folder, @PathVariable("id") String id,
@PathVariable("name") String name, @PathVariable("ext") String ext, HttpServletResponse response){ @PathVariable(value = "name",required = false) String name, @PathVariable(value = "ext", required = false) String ext,
File file = diskCoreService.getFile(folder,id); @RequestHeader(value = "authcode",required = false) String authcode,
@RequestParam(value = "authcode",required = false) String checkcode,HttpServletResponse response){
File file = diskCoreService.getFile(folder,id, StringUtils.isEmpty(authcode)?checkcode:authcode);
response.setHeader("Content-Disposition", "attachment;filename="+getFileName(file.getName())); response.setHeader("Content-Disposition", "attachment;filename="+getFileName(file.getName()));
this.sendRespose(response, file); this.sendRespose(response, file);
} }
@GetMapping(value = "net-disk/file/{folder}/{id}/{name}.{ext}") @GetMapping(value = "net-disk/files/{folder}/{id}/{name}.{ext}")
@ResponseStatus(HttpStatus.OK) @ResponseStatus(HttpStatus.OK)
public void open(@PathVariable("folder") String folder, @PathVariable("id") String id, public void open(@PathVariable("folder") String folder, @PathVariable("id") String id,
@PathVariable("name") String name, @PathVariable("ext") String ext, HttpServletResponse response){ @PathVariable("name") String name, @PathVariable("ext") String ext,
File file = diskCoreService.getFile(folder,id); @RequestHeader(value = "authcode",required = false) String authcode,
@RequestParam(value = "authcode",required = false) String checkcode,HttpServletResponse response){
File file = diskCoreService.getFile(folder,id,StringUtils.isEmpty(authcode)?checkcode:authcode);
String type = getType(ext); String type = getType(ext);
response.setContentType(type); response.setContentType(type);
if(type.toLowerCase().equals("application/octet-stream")) if(type.toLowerCase().equals("application/octet-stream"))
...@@ -86,16 +97,53 @@ public class DiskCoreResource ...@@ -86,16 +97,53 @@ public class DiskCoreResource
this.sendRespose(response, file); this.sendRespose(response, file);
} }
@Value("ibiz.file.proxy.previewpath")
private String previewPath;
@GetMapping(value = "net-disk/preview/{folder}/{id}/{name}.{ext}") @GetMapping(value = "net-disk/preview/{folder}/{id}/{name}.{ext}")
@ResponseStatus(HttpStatus.OK) public ResponseEntity preview(@PathVariable("folder") String folder, @PathVariable("id") String id,
public void preview(@PathVariable("folder") String folder, @PathVariable("id") String id, @PathVariable("name") String name, @PathVariable("ext") String ext,
@PathVariable("name") String name, @PathVariable("ext") String ext, HttpServletResponse response){ @RequestHeader(value = "authcode",required = false) String authcode,
File file = diskCoreService.getFile(folder,id); @RequestParam(value = "authcode",required = false) String checkcode, HttpServletRequest request){
String type = getType(ext); if(StringUtils.isEmpty(previewPath))
response.setContentType(type); throw new BadRequestAlertException("未配置预览系统地址","SDFile","");
if(type.toLowerCase().equals("application/octet-stream")) String redirectUrl = request.getScheme().concat("://").concat(request.getServerName());
response.setHeader("Content-Disposition", "attachment;filename="+getFileName(file.getName())); if(request.getServerPort()!=80&&request.getServerPort()!=443)
this.sendRespose(response, file); redirectUrl=redirectUrl.concat(":").concat(request.getServerPort()+"");
redirectUrl=redirectUrl.concat("/net-disk/download/")
.concat(folder).concat("/").concat(folder).concat("/").concat(name).concat(".").concat(ext).concat("?authcode=").concat(StringUtils.isEmpty(authcode)?checkcode:authcode);
redirectUrl=previewPath.concat("?url=").concat(encodeURIComponent(redirectUrl));
return ResponseEntity.status(HttpStatus.MOVED_PERMANENTLY).header(HttpHeaders.LOCATION, redirectUrl).build();
}
@Value("ibiz.file.proxy.ocrpath")
private String ocrPath;
@GetMapping(value = "net-disk/ocrview/{folder}/{id}/{name}.{ext}")
public ResponseEntity ocrview(@PathVariable("folder") String folder, @PathVariable("id") String id,
@PathVariable("name") String name, @PathVariable("ext") String ext,
@RequestHeader(value = "authcode",required = false) String authcode,
@RequestParam(value = "authcode",required = false) String checkcode, HttpServletRequest request){
if(StringUtils.isEmpty(previewPath))
throw new BadRequestAlertException("未配置预览系统地址","SDFile","");
String redirectUrl = request.getScheme().concat("://").concat(request.getServerName());
if(request.getServerPort()!=80&&request.getServerPort()!=443)
redirectUrl=redirectUrl.concat(":").concat(request.getServerPort()+"");
redirectUrl=redirectUrl.concat("/net-disk/download/")
.concat(folder).concat("/").concat(folder).concat("/").concat(name).concat(".").concat(ext).concat("?authcode=").concat(StringUtils.isEmpty(authcode)?checkcode:authcode);
redirectUrl=ocrPath.concat("?url=").concat(encodeURIComponent(redirectUrl));
return ResponseEntity.status(HttpStatus.MOVED_PERMANENTLY).header(HttpHeaders.LOCATION, redirectUrl).build();
}
@GetMapping(value = "net-disk/files/{ownertype}/{ownerid}")
public ResponseEntity<List<FileItem>> getFiles(@PathVariable("ownertype") String ownertype, @PathVariable("ownerid") String ownerid){
return ResponseEntity.ok().body(diskCoreService.getFileList(ownertype,ownerid));
}
@PostMapping(value = "net-disk/files/{ownertype}/{ownerid}")
public ResponseEntity<Boolean> saveFiles(@PathVariable("ownertype") String ownertype, @PathVariable("ownerid") String ownerid, @RequestBody List<FileItem> fileItems){
diskCoreService.saveFileList(ownertype,ownerid,fileItems);
return ResponseEntity.ok().body(true);
} }
protected void sendRespose(HttpServletResponse response, File file){ protected void sendRespose(HttpServletResponse response, File file){
...@@ -142,4 +190,25 @@ public class DiskCoreResource ...@@ -142,4 +190,25 @@ public class DiskCoreResource
} }
return fileName; return fileName;
} }
protected String encodeURIComponent(String s) {
String result = null;
try {
result = java.net.URLEncoder.encode(s, "UTF-8")
.replaceAll("\\+", "%20")
.replaceAll("\\!", "%21")
.replaceAll("\\'", "%27")
.replaceAll("\\(", "%28")
.replaceAll("\\)", "%29")
.replaceAll("\\~", "%7E");
}
// This exception should never occur.
catch (UnsupportedEncodingException e) {
result = s;
}
return result;
}
} }
\ No newline at end of file
...@@ -18,4 +18,14 @@ public class FileItem ...@@ -18,4 +18,14 @@ public class FileItem
private String filename; private String filename;
private long size; private long size;
private String ext; private String ext;
private String authcode;
public FileItem(String id, String name, String fileid, String filename, long size, String ext) {
this.id = id;
this.name = name;
this.fileid = fileid;
this.filename = filename;
this.size = size;
this.ext = ext;
}
} }
package cn.ibizlab.util.rest; package cn.ibizlab.util.rest;
import cn.ibizlab.util.domain.FileItem;
import cn.ibizlab.util.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@Slf4j
@RestController
@RequestMapping("/")
public class FileController public class FileController
{ {
@Autowired
private FileService fileService;
@PostMapping(value = "${ibiz.file.uploadpath:ibizutil/upload}")
public ResponseEntity<FileItem> upload(@RequestParam("file") MultipartFile multipartFile){
return ResponseEntity.ok().body(fileService.saveFile(multipartFile));
}
private final String defaultdownloadpath="ibizutil/download/{id}";
@GetMapping(value = "${ibiz.file.downloadpath:"+defaultdownloadpath+"}")
@ResponseStatus(HttpStatus.OK)
public void download(@PathVariable String id, HttpServletResponse response){
File file= fileService.getFile(id);
response.setHeader("Content-Disposition", "attachment;filename="+getFileName(file.getName()));
this.sendRespose(response, file);
}
protected void sendRespose(HttpServletResponse response, File file){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(file));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
}
catch (Exception e) {
//throw e;
}
finally {
if (bis != null) {
try {
bis.close();
}
catch (IOException e) {
}
}
if (bos != null) {
try {
bos.close();
}
catch (IOException e) {
}
}
}
}
protected String getFileName(String fileName){
try {
return new String(fileName.getBytes("utf-8"),"iso8859-1");//防止中文乱码
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return fileName;
}
} }
\ No newline at end of file
package cn.ibizlab.util.service;
import cn.ibizlab.util.domain.FileItem;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
public interface FileService
{
FileItem saveFile(MultipartFile multipartFile);
File getFile(String fileid);
}
\ No newline at end of file
package cn.ibizlab.util.service;
public class SimpleUserService {
}
Markdown 格式
0% or
您添加了 0 到此讨论。请谨慎行事。
先完成此消息的编辑!
想要评论请 注册