vue+springboot文件下載


//vue element-ui
<el-button size="medium" type="primary" @click="download">導出</el-button>
  //js
  downLoad(){
     window.location.href="/api/downLoad";
  },
 
//后台java

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class DownLoadFile {

  private static Logger log = LoggerFactory.getLogger(DownLoadFile.class);

  @RequestMapping(value = "/downLoad", method = RequestMethod.GET)
  public static final String downLoad(HttpServletResponse res) throws UnsupportedEncodingException {
    Map<String, Object> reMap = new HashMap<>();
    //文件名 可以通過形參傳進來
    String fileName = "t_label.txt";
    //要下載的文件地址 可以通過形參傳進來
    String filepath = "f:/svs/" + fileName;

    OutputStream os = null;
    InputStream is = null;
    try {
      // 取得輸出流
      os = res.getOutputStream();
      // 清空輸出流
      res.reset();
      res.setContentType("application/x-download;charset=GBK");
      res.setHeader("Content-Disposition",
        "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso-8859-1"));
      // 讀取流
      File f = new File(filepath);
      is = new FileInputStream(f);
      if (is == null) {
        reMap.put("msg", "下載附件失敗");
      }
      // 復制
      IOUtils.copy(is, res.getOutputStream());
        res.getOutputStream().flush();
      } catch (IOException e) {
        reMap.put("msg", "下載附件失敗,error:" + e.getMessage());
      }
      // 文件的關閉放在finally中
      finally {
        try {
          if (is != null) {
            is.close();
          }
        } catch (IOException e) {
          log.error(e.toString());
        }
        try {
          if (os != null) {
            os.close();
          }
        } catch (IOException e) {
          log.error(e.toString());
        }
      }
      String str = JsonUtil.map2Json(reMap);
      return str;
    }

}

說明:此代碼用火狐瀏覽器測試的時候沒問題,谷歌版本以及設置不一樣可能會出現文件下載錯誤,甚至不直接彈出另存為的對話框


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM