package com.saye.hospitalgd.controller.system;

import com.saye.hospitalgd.commons.date.DateDUtil;
import com.saye.hospitalgd.model.StatusDefine;
import com.saye.hospitalgd.commons.string.StringDUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @author thuang
 * @version 1.0
 * @description: TODO
 * @date 2021/5/24 13:56
 */
@Controller
public class downloadController {

    @RequestMapping("/download")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception{

        try {
            String fileName = StringDUtil.changeNullToEmpty(request.getParameter("fileName"));
            String dowloadName = StringDUtil.changeNullToEmpty(request.getParameter("dowloadName"));
            //过滤相对路径../
            int lastIndex = fileName.lastIndexOf(".");
            //fileName = fileName.substring(0, lastIndex).replaceAll(".", "")+fileName.substring(lastIndex);
            String savePath = StatusDefine.filePath + fileName ;
            File file = new File(savePath);
            FileInputStream fis = new FileInputStream(file);
            response.setContentType("application/force-download");
            response.addHeader("Content-disposition", "attachment;fileName=" + URLEncoder.encode(dowloadName+ DateDUtil.getCurrentDate(DateDUtil.yyyy_MM_dd)+".xlsx", "UTF-8"));
            OutputStream os = response.getOutputStream();
            byte[] buf = new byte[1024];
            int len = 0;
            while((len = fis.read(buf)) != -1) {
                os.write(buf, 0, len);
            }
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
