CharlsLin / CareerExperience

1 stars 1 forks source link

#1 Files, Files download, packing files into ZIP #1

Open CharlsLin opened 4 years ago

CharlsLin commented 4 years ago

ArrayList of Files ⇒ ZIP ダウンロード

https://www.jianshu.com/p/7cabe09ce563

CharlsLin commented 4 years ago

使用google io工具类,避免缓存时文件名产生随机数

import com.google.common.io.Files;

File file= null;
String fileName = null;
file = new File(Files.createTempDir(), fileName );
CharlsLin commented 4 years ago

CSV文件下载思路

  1. 创建一个CSVBean.java,写入要输出到CSV文件的属性,比如说id, name, age, sex.... 可通过各种注释来设置文件头部内容,比如:

    
    //不设置头部
    @CsvEntity(header = false)
    public class CSVBean{
    
    //csv文件的列
    @CsvColumn
    private String name;
    
    @CsvColumn
    private String id;
    ...
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name= name;
    }
    
    public String getId() {
        return id;
    }
    
    public void setId(String id) {
        this.id= id;
    }

}


2. 创建一个 CSVBeanService.java,用于取得数据,并设置到CSVBean类属性里去。
```java
@Service
public class CSVBeanService{

 @Autowired
UserService uSerService;

public List<CSVBean>createCsvList(List<User>list, String Param1,String Param2) {

    List<CSVBean > csvList= new ArrayList<CSVBean >();

   //循环赋值
   for (User user: list) {
      //创建新的一条数据
    CSVBean cb = new CSVBean();

    cb.setId(uSerService.findById(Param1));
    cb.setName(Param2);
    ...
}
    return csvList;
}
}
  1. 在Controller.java调用 CSVBeanService.java,使用OutputStream下载CSV文件

@Controller public class downLoadController{

@Autowired CSVBeanService cSVBeanService;

private String download(List list, HttpServletResponse res, String Param1, String Param2) throws Exception { // 调用service方法 List CsvList = cSVBeanService.createCsvList(list, Param1,Param2);

File file = null;
String fileName = null;
//生成cookie的key和value
Cookie cookie = new Cookie("downloaded", "yes");
cookie.setPath("/");
// 内容设置
file = File.createTempFile("download", "tmp");
CsvIOUtil.writeCsv(file, CsvList , "\r\n", ',', true, CSVBean .class);

// response設定
res.setCharacterEncoding("Windows-31J");
res.setContentType( "application/octet-stream"+ ";charset="+ "Windows-31J");
res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
res.setHeader("Cache-Control", "no-store");
res.setHeader("Pragma", "no-cache");
res.addHeader("Content-Length", String.valueOf(file.length()));

FileUtils.copyFile(file, res.getOutputStream());
res.getOutputStream().flush();

} }

4. 下载完成后刷新页面(js)
```javascript
 setInterval(function() {
        var value = GetCookie("downloaded");
        if (value == "yes") {
          setTimeout(function() {
            window.location.href = 下载完成后调用的action;
          }, 1000);//👈设置timeout
        }
        deleteCookie("downloaded");
      }, 1000);//👈设置timeout