package com.example.filetransfer.control;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@Controller
public class HelloWordControl {

    @RequestMapping("/hello")
    @ResponseBody
    public String HelloWord(){
        return "你好吗,我很好!";
    }

    @RequestMapping("/downloadZip")
    public ResponseEntity<byte[]> downloadZip(HttpServletResponse response)throws IOException {
        String path="D:\\工具包\\apache-activemq-5.16.2\\activemq-all-5.16.2.jar";
         return buildResponseEntity(new File(path));
    }


    /**
     * 构建下载类
     * @param file
     * @return
     * @throws IOException
     */
    public static ResponseEntity<byte[]> buildResponseEntity(File file) throws IOException {
        byte[] body = null;
        //获取文件
        InputStream is = new FileInputStream(file);
        body = new byte[is.available()];
        is.read(body);
        HttpHeaders headers = new HttpHeaders();
        //设置文件类型
        headers.add("Content-Disposition", "attchement;filename=" + file.getName());
        //设置Http状态码
        HttpStatus statusCode = HttpStatus.OK;
        //返回数据
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
        return entity;
    }
}