【springmvc】下載檔案

小魏的馬仔發表於2017-04-06
package com.ytang.ec.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Component
public class MyDownload{

    public void downloadSolve(String filePath,HttpServletRequest request, HttpServletResponse response, String shopNick, String yearMonth) throws ServletException, IOException {

        //得到該檔案
        File file = new File(filePath);
        if(!file.exists()){
            System.out.println("Have no such file!");
            return;//檔案不存在就退出方法
        }

        FileInputStream fileInputStream = new FileInputStream(file);
        //設定Http響應頭告訴瀏覽器下載這個附件
        response.setHeader("Content-Disposition", "attachment;Filename=" + URLEncoder.encode(yearMonth+shopNick+".xls", "UTF-8"));
        OutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[2048];
        int len = 0;
        while ((len = fileInputStream.read(bytes))>0){
            outputStream.write(bytes,0,len);
        }
        fileInputStream.close();
        outputStream.close();

        //刪除該檔案
        file.delete();
    }
}

相關文章