package com.moti.controller;
import com.moti.entity.FileFolder;
import com.moti.entity.FileStore;
import com.moti.entity.MyFile;
import com.moti.entity.TempFile;
import com.moti.utils.FtpUtil;
import com.moti.utils.LogUtils;
import com.moti.utils.QRCodeUtil;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @ClassName: FileStoreController
* @Description: 文件仓库控制器
* @author: xw
* @date 2020/2/6 16:04
* @Version: 1.0
**/
@Controller
public class FileStoreController extends BaseController {
private Logger logger = LogUtils.getInstance(FileStoreController.class);
/**
* @Description 上传临时文件
* @Author xw
* @Date 23:14 2020/3/9
* @Param [files]
* @return void
**/
@PostMapping("/uploadTempFile")
public String uploadTempFile(@RequestParam("file") MultipartFile file,String url) {
session.setAttribute("imgPath","https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2654852821,3851565636&fm=26&gp=0.jpg");
String name = file.getOriginalFilename().replaceAll(" ","");
if (!checkTarget(name)){
logger.error("临时文件上传失败!文件名不符合规范...");
session.setAttribute("msg", "上传失败!文件名不符合规范");
return "redirect:/temp-file";
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = format.format(new Date());
String path = "temp/"+dateStr +"/"+UUID.randomUUID();
try {
if (FtpUtil.uploadFile("/"+path, name, file.getInputStream())){
//上传成功
logger.info("临时文件上传成功!"+name);
String size = String.valueOf(file.getSize());
TempFile tempFile = TempFile.builder().fileName(name).filePath(path).size(size).uploadTime(new Date()).build();
if (tempFileService.insert(tempFile)) {
try {
String id = UUID.randomUUID().toString();
String p = request.getSession().getServletContext().getRealPath("/user_img/");
Long t = tempFile.getUploadTime().getTime();
url = url+"/file/share?t="+ UUID.randomUUID().toString().substring(0,10) +"&f="+tempFile.getFileId()+"&p="+size+"&flag=2";
File targetFile = new File(p, "");
if (!targetFile.exists()) {
targetFile.mkdirs();
}
File f = new File(p, id + ".jpg");
if (!f.exists()){
//文件不存在,开始生成二维码并保存文件
OutputStream os = new FileOutputStream(f);
QRCodeUtil.encode(url, "/static/img/logo.png", os, true);
os.close();
}
//异步删除临时文件
tempFileService.deleteById(tempFile.getFileId());
session.setAttribute("imgPath","user_img/"+id+".jpg");
session.setAttribute("url",url);
session.setAttribute("msg","上传成功,扫码/访问链接 即可下载!");
return "redirect:/temp-file";
} catch (Exception e) {
e.printStackTrace();
}
}else {
logger.info("临时文件数据库写入失败!"+name);
session.setAttribute("url","error");
session.setAttribute("msg", "服务器出错了,临时文件上传失败!");
}
}else{
//上传失败
logger.info("临时文件上传失败!"+name);
session.setAttribute("url","error");
session.setAttribute("msg", "服务器出错了,上传失败!");
}
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/temp-file";
}
/**
* @Description 网盘的文件上传
* @Author xw
* @Date 23:10 2020/2/10
* @Param [files]
* @return java.util.Map<java.lang.String,java.lang.Object>
**/
@PostMapping("/uploadFile")
@ResponseBody
public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile files) {
Map<String, Object> map = new HashMap<>();
if (fileStoreService.getFileStoreByUserId(loginUser.getUserId()).getPermission() != 0){
logger.error("用户没有上传文件的权限!上传失败...");
map.put("code", 499);
return map;
}
FileStore store = fileStoreService.getFileStoreByUserId(loginUser.getUserId());
Integer folderId = Integer.valueOf(request.getHeader("id"));
String name = files.getOriginalFilename().replaceAll(" ","");
//获取当前目录下的所有文件,用来判断是否已经存在
List<MyFile> myFiles = null;
if (folderId == 0){
//当前目录为根目录
myFiles = myFileService.getRootFilesByFileStoreId(loginUser.getFileStoreId());
}else {
//当前目录为其他目录
myFiles = myFileService.getFilesByParentFolderId(folderId);
}
for (int i = 0; i < myFiles.size(); i++) {
if ((myFiles.get(i).getMyFileName()+myFiles.get(i).getPostfix()).equals(name)){
logger.error("当前文件已存在!上传失败...");
map.put("code", 501);
return map;
}
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = format.format(new Date());
String path = loginUser.getUserId()+"/"+dateStr +"/"+folderId;
if (!checkTarget(name)){
logger.error("上传失败!文件名不符合规范...");
map.put("code", 502);
return map;
}
Integer sizeInt = Math.toIntExact(files.getSize() / 1024);
//是否仓库放不下该文件
if(store.getCurrentSize()+sizeInt > store.getMaxSize()){
logger.error("上传失败!仓库已满。");
map.put("code", 503);
return map;
}
//处理文件大小
String size = String.valueOf(files.getSize()/1024.0);
int indexDot = size.lastIndexOf(".");
size = size.substring(0,indexDot);
int index = name.lastIndexOf(".");
String tempName = name;
String postfix = "";
int type = 4;
if (index!=-1){
tempName = name.substring(index);
name = name.substring(0,index);
//获得文件类型
type = getType(tempName.toLowerCase());
postfix = tempName.toLowerCase();
}
try {
//提交到FTP服务器
boolean b = FtpUtil.uploadFile("/"+path, name + postfix, files.getInputStream());
if (b){
//上传成功
logger.info("文件上传成功!"+files.getOriginalFilename());
//向数据库文件表写入数据
myFileService.addFileByFileStoreId(
MyFile.builder()
.myFileName(name).fileStoreId(loginUser.getFileStoreId()).myFilePath(path)