package com.ruoyi.web.controller.back;

import com.ruoyi.system.config.AliConfig;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RequestMapping("/file")
@RestController
public class FileController {

    /**
     * 下载OSS文件
     */
    @GetMapping("/download/{objectName}/{fileName}")
    public void downloadOssFile(@PathVariable String objectName,@PathVariable String fileName, HttpServletResponse response) {
        try {
            String[] file = objectName.split("file/download");
            // 获取文件字节
            byte[] data = AliConfig.ossDown(objectName+"/"+fileName);
            // 设置响应头，支持中文文件名
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
            assert data != null;
            response.getOutputStream().write(data);
            response.getOutputStream().flush();
        } catch (Exception e) {
            try {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"msg\":\"下载失败: " + e.getMessage() + "\"}");
            } catch (Exception ignored) {}
        }
    }

}
