package com.example.demo.controller;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.FileUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
@RestController
@RequestMapping("file")
public class TestController {
@GetMapping(value = "/test1")
public void test(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
// 设置编码
response.setCharacterEncoding("UTF-8");
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
String path = "D://logs/" + fileName;
try {
FileInputStream in = new FileInputStream(new File(path));
FileCopyUtils.copy(in, response.getOutputStream());
} catch (FileNotFoundException e) {
System.out.println("文件不存在")
} catch (IOException e) {
e.printStackTrace();
}
}
@RequestMapping("download")
public void download(String filename, HttpServletResponse res) throws IOException {
String path = "D://logs/"+filename;
res.setCharacterEncoding("UTF-8");
// attachment是以附件的形式下载,inline是浏览器打开
res.setHeader("Content-Disposition", "inline;filename="+filename+".txt");
res.setContentType("text/plain;UTF-8");
// 把二进制流放入到响应体中
ServletOutputStream os = res.getOutputStream();
File file = new File(path);
byte[] bytes = FileUtils.readFileToByteArray(file);
os.write(bytes);
os.flush();
os.close();
}
}