首页 > 其他 > 详细

FileUploadController

时间:2020-07-15 15:45:25      阅读:54      评论:0      收藏:0      [点我收藏+]
@Slf4j
@Controller
@RequestMapping(value = "/upload")
public class JkFileUploadController {

    private static final String UPLOAD_FILE_PATH = "upload/jk/files";

    @Value("${data.attachment}")
    public String root;

    @Value("${domain}")
    public String domain;

    @Resource
    private ResourceLoader resourceLoader;
    
    /**
     * 允许上传文件的格式
     */
    private static final String[] FILE_TYPE = new String[]{".doc", ".ppt", ".pdf", ".xls", ".xlsx", ".gif", ".jpeg", ".bmp", ".jpg", ".png"};

    @PostMapping(value = "/jk/files")
    public ResponseEntity<String> uploadAllFile(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty() || !FileValidateUtil.validateType(file, FILE_TYPE)) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
        String path = getFilePath(file.getOriginalFilename());
        String docUrl = StringUtils.replace(StrUtil.subSuf(path, root.length()), "\\", "/");
        try {
            File newFile = new File(path);
            file.transferTo(newFile);
            return ResponseEntity.status(HttpStatus.OK).body(domain + docUrl);
        } catch (IOException e) {
            log.error("上传文件错误!" + e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/jk/files/{filename:.+}")
    public ResponseEntity<?> getFile(@PathVariable String filename) {
        try {
            String filePath = StringUtils.replace(Paths.get(root, UPLOAD_FILE_PATH, filename).toString(), "\\", "/");
            return ResponseEntity.ok(resourceLoader.getResource("file:" + filePath));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseEntity.notFound().build();
        }
    }

    private String getFilePath(String sourceFileName) {
        String baseFolder = root + File.separator + UPLOAD_FILE_PATH;
        File file = new File(baseFolder);
        if (!file.isDirectory()) {
            if (!file.mkdirs()) {
                log.info("目录创建失败");
            }
        }
        // 生成新的文件名
        String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmssSSS") + RandomUtils.nextInt(100, 9999) + "." + StringUtils.substringAfterLast(sourceFileName, ".");
        return baseFolder + File.separator + fileName;
    }
}

 

FileUploadController

原文:https://www.cnblogs.com/xiaomaoyvtou/p/13305399.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!