package cn.com.qmth.examcloud.tool.controller;

import cn.com.qmth.examcloud.tool.config.SysProperty;
import cn.com.qmth.examcloud.tool.utils.DateHelper;
import cn.com.qmth.examcloud.tool.utils.FileHelper;
import cn.com.qmth.examcloud.tool.utils.StatusException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@Controller
public class UploadController extends BaseController {

    private final static Logger log = LoggerFactory.getLogger(UploadController.class);

    @Autowired
    private SysProperty sysProperty;

    @ResponseBody
    @PostMapping(value = "/upload")
    public String upload(@RequestPart(value = "file", required = false) MultipartFile file) throws Exception {
        if (file == null) {
            throw new StatusException("上传文件不能为空！");
        }

        final String tempDir = sysProperty.getDataDir() + "/data";
        FileHelper.makeDirs(tempDir);

        final String newFileName = DateHelper.currentTimeMillis() + FileHelper.getFileSuffix(file.getOriginalFilename());
        final String filePath = tempDir + "/" + newFileName;
        FileHelper.saveToFile(file.getBytes(), new File(filePath));

        log.info("上传文件成功！{}", filePath);
        return filePath;
    }

}
