You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
82 lines
3.1 KiB
82 lines
3.1 KiB
package com.iflytop.nuclear.controller;
|
|
|
|
import com.alibaba.fastjson2.JSONObject;
|
|
import com.iflytop.nuclear.service.UploadService;
|
|
import com.iflytop.nuclear.utils.ResponseData;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.security.access.prepost.PreAuthorize;
|
|
import org.springframework.stereotype.Controller;
|
|
import org.springframework.web.bind.annotation.*;
|
|
import org.springframework.web.multipart.MultipartFile;
|
|
|
|
import java.io.File;
|
|
import java.io.IOException;
|
|
import java.text.SimpleDateFormat;
|
|
import java.util.Date;
|
|
import java.util.HashSet;
|
|
import java.util.Set;
|
|
|
|
/**
|
|
* @author cool
|
|
* @date 2023/6/27 09:53
|
|
* @desc 上传接口
|
|
*/
|
|
@Slf4j
|
|
@RestController
|
|
@CrossOrigin
|
|
@PreAuthorize("hasRole('ADMIN')")
|
|
public class UploadController {
|
|
|
|
@Autowired
|
|
UploadService uploadService;
|
|
|
|
@PostMapping("/upload/{id}")
|
|
public ResponseData uploadToLocal(MultipartFile file, @PathVariable(name = "id") int taskId) throws IOException {
|
|
// 对当前文件中内容格式进行校验
|
|
boolean isValid = uploadService.verifyFileFormat(file);
|
|
if (!isValid) {
|
|
return ResponseData.fail("上传文件内容未按照标准版式排版");
|
|
}
|
|
boolean isSuccess = uploadService.saveFileContentToDB(file, taskId);
|
|
// 获取文件原本的名字
|
|
String originName = file.getOriginalFilename();
|
|
// 判断文件是否是pdf文件
|
|
Set<String> set = new HashSet<>();
|
|
set.add(".xlsx");
|
|
// 取出文件的后缀
|
|
int count = 0;
|
|
for(int i = 0; i < originName.length(); i++){
|
|
if(originName.charAt(i) == '.'){
|
|
count = i;
|
|
break;
|
|
}
|
|
}
|
|
String endName = originName.substring(count); //取出文件类型
|
|
String fileType = originName.substring(count + 1); //文件类型
|
|
if(!set.contains(endName)){
|
|
return ResponseData.fail("上传的文件类型错误,只能上传xlsx类型的文件");
|
|
}
|
|
// 创建保存路径 后期使用保存在数据库中的id进行取名
|
|
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
|
|
String format = sdf.format(new Date());
|
|
String savePath = System.getProperty("user.dir") + "/" + "uploadfiles" + "/" + fileType + "/" + format;
|
|
// String savePath = "/home/zwsd/" + "uploadfiles" + "/" + fileType + "/" + format;
|
|
// 保存文件的文件夹
|
|
File folder = new File(savePath);
|
|
// 判断路径是否存在,不存在则自动创建
|
|
if(!folder.exists()){
|
|
folder.mkdirs();
|
|
}
|
|
String saveName = originName.substring(0, count) + "-" + taskId + ".xlsx";
|
|
try {
|
|
file.transferTo(new File(folder,saveName));
|
|
String filePath = savePath + "\\" + saveName;
|
|
JSONObject res = new JSONObject();
|
|
res.put("path", filePath);
|
|
return ResponseData.success(res);
|
|
} catch (IOException e){
|
|
return ResponseData.fail(e.getMessage());
|
|
}
|
|
}
|
|
}
|