package com.playlet.web.controller.tool;

import com.playlet.common.core.domain.Result;
import com.playlet.web.service.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>文件上传</p>
 * @author clunt
 */
@RestController
@Api(tags = "通用*文件上传")
@RequestMapping(value = "/tool/oss")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class OssFileController {

    private final OssService ossService;

    @ResponseBody
    @PostMapping(value = "/upload")
    @ApiOperation(value = "文件上传接口,返回文件的url地址", httpMethod = "POST")
    public Result<String> upload(@RequestPart @RequestParam("file") MultipartFile multipartFile) {
        try {
            return Result.success(ossService.upload(multipartFile));
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

    @PostMapping(value = "/uploadFromPlaylet")
    @ResponseBody
    public Result<String> uploadFile(MultipartFile file) {
        try {
//            String name = request.getParameter("name");
            // 转型为MultipartHttpRequest：
//            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            // 获得实际：
//            MultipartFile file= multipartRequest.getFile(name);
            // 上传后返回的文件路径
            return Result.success(ossService.upload(file));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}
