package com.dgtly.api.controller;


import com.dgtly.common.annotation.ApiPassToken;
import com.dgtly.common.config.Global;
import com.dgtly.common.config.ServerConfig;
import com.dgtly.common.core.domain.AjaxResult;
import com.dgtly.common.utils.file.FileUploadUtils;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class CommonController {


    @Autowired
    private ServerConfig serverConfig;
    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    @ResponseBody
    @ApiPassToken
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = Global.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.putKV("fileName", fileName);
            ajax.putKV("url", url);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
}
