package com.ruoyi.web.controller.system;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.ServerConfig;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/file")
public class UploadAndDownloadController {
    @Autowired
    private ServerConfig serverConfig;

    /**
     * 上传文件
     */
    /**
     * 文件上传接口
     */
    @ApiOperation(value = "上传文件", notes = "上传文件接口")
    @RequestMapping(value = "/upload", method = RequestMethod.POST, headers = "content-type=multipart/form-data")
    public AjaxResult uploadFile(@RequestPart("file") MultipartFile file) throws Exception
    {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            if (filePath == null){
                throw new RuntimeException("文件路径不存在");
            }
            //上传并返回文件名
            String filename = FileUploadUtils.upload(filePath, file);
            if (filename == null){
                throw new RuntimeException("文件名称不存在");
            }
            String url = serverConfig.getUrl()+filename;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName",filename);
            ajax.put("url",url);
            return ajax;
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }
}
