zqy
5 天以前 b02beccf4567068cb47a3f1181a00039456c872d
zhang-content/src/main/java/com/ruoyi/service/impl/DownLoadFileServiceImpl.java
@@ -1,7 +1,13 @@
package com.ruoyi.service.impl;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.service.DownLoadFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
@@ -13,44 +19,26 @@
 * @Date 2023-03-19 17:33
 */
@Service
@Slf4j
public class DownLoadFileServiceImpl implements DownLoadFileService {
    @Override
    public AjaxResult downLoadFile(String path, HttpServletResponse response) {
        File file = new File(path);
        byte[] buffer = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
    @Override
    public void downLoadFile(String path, HttpServletResponse response) {
        path = path.substring(8);
        try {
            //文件是否存在
            if (file.exists()) {
                //设置响应
                response.setContentType("application/octet-stream;charset=UTF-8");
                response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
                response.setHeader("Content-Disposition","attachment;filename=");
                response.setCharacterEncoding("UTF-8");
                os = response.getOutputStream();
                bis = new BufferedInputStream(new FileInputStream(file));
                while(bis.read(buffer) != -1){
                    os.write(buffer);
                }
                return AjaxResult.success("操作成功");
            if (!FileUtils.checkAllowDownload(path)) {
                throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", path));
            }
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(bis != null) {
                    bis.close();
                }
                if(os != null) {
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            String realFileName = System.currentTimeMillis() + path.substring(path.indexOf("_") + 1);
            String filePath = RuoYiConfig.getProfile() + path;
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
        return AjaxResult.error("操作失败");
    }
}