package com.bupt.note.Controller; import com.bupt.note.Repository.FileRepository; import com.bupt.note.ResponseData.ResponseData; import com.bupt.note.ResponseData.ResponseDataUtil; import com.bupt.note.dto.FileForm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import org.springframework.util.ResourceUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.Optional; import java.util.UUID; /** * 论文文本管理接口 */ @RestController @RequestMapping(value = "/v1/api/file") public class FileController { @Value("${spring.resources.static-locations}") private String txtPath; private static Logger logger = LoggerFactory.getLogger(FileController.class); @Autowired private FileRepository fileRepository; //上传论文文本 @PostMapping("upload") public ResponseData upload(FileForm fileForm){ MultipartFile file=fileForm.getFile(); if(file!=null&& MediaType.TEXT_PLAIN_VALUE.equals(file.getContentType())){ File txtFile; File txtDir; try { txtDir=new File(URLDecoder.decode(ResourceUtils.getURL("classpath:").getPath(), StandardCharsets.UTF_8) + txtPath.replace("classpath:/", "")); if(!txtDir.exists()&&txtDir.mkdirs()){ logger.info("成功初始化上传论文目录:"+txtDir.getAbsolutePath()); } txtFile=new File(txtDir, UUID.randomUUID()+".txt"); logger.debug("论文保存到"+txtFile.getAbsolutePath()); file.transferTo(txtFile); com.bupt.note.Model.File f=new com.bupt.note.Model.File(); f.setFilePath(txtFile.getAbsolutePath()); f.setUrlPath("/txt/"+txtFile.getName()); fileRepository.save(f); return ResponseDataUtil.buildSuccess(f.getId()); } catch (IOException e) { logger.error(String.valueOf(e)); e.printStackTrace(); return ResponseDataUtil.buildError(); } }else{ return ResponseDataUtil.buildError(); } } @GetMapping("find/{id}") public ResponseData get(@PathVariable Long id){ if(fileRepository.existsById(id)){ com.bupt.note.Model.File file= fileRepository.getOne(id); return ResponseDataUtil.buildSuccess(file.getUrlPath()); }else{ return ResponseDataUtil.buildError(); } } /** * 删除论文文本文件 * @param id 文件id * @return */ @DeleteMapping("remove/{id}") public ResponseData remove(@PathVariable Long id){ if(fileRepository.existsById(id)){ Optional f=fileRepository.findById(id); if(f.isPresent()){ File txtFile=new File(f.get().getFilePath()); if(txtFile.exists()&&txtFile.delete()) { fileRepository.deleteById(id); return ResponseDataUtil.buildSuccess(); }else{ return ResponseDataUtil.buildError(); } }else { return ResponseDataUtil.buildError(); } }else{ return ResponseDataUtil.buildError(); } } }