vue axios+springboot 檔案下載

渺小砂礫發表於2018-09-07

以下是一個比較完整的流程

後端程式碼如下:

controller:

@RequestMapping(value = "/download", method = RequestMethod.GET)
public String downloadData(HttpServletResponse res) {
    String data="這是一個下載檔案";   //傳入資料
    File file=new File("檔案.txt");
    FileUtils.getFile(data.getBytes(),file.getName());
    FileUtils.responseTo(file,res);
    file.delete();
    System.out.println("success");
    return "success";
}
複製程式碼

工具類如下:

public class FileUtils {

public static void getFile(byte[] bfile, String fileName) {    //建立檔案
    File file=new File(fileName);
    try {
        if (!file.exists()){file.createNewFile();}
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(bfile);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static void responseTo(File file, HttpServletResponse res) {  //將檔案傳送到前端
    res.setHeader("content-type", "application/octet-stream");
    res.setContentType("application/octet-stream");
    res.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
    byte[] buff = new byte[1024];
    BufferedInputStream bis = null;
    OutputStream os = null;
    try {
        os = res.getOutputStream();
        bis = new BufferedInputStream(new FileInputStream(file));
        int i = bis.read(buff);
        while (i != -1) {
            os.write(buff, 0, buff.length);
            os.flush();
            i = bis.read(buff);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    System.out.println("success");
}
}
複製程式碼

前端檔案接收:

axios({
    url: '/gafzpt/capital/download',
    method: 'get',
    params: {
      capitalId: capitalId
    },
    responseType: 'blob'     //接收型別設定,否者返回字元型
  })
    .then(res => {           //定義檔名等相關資訊
      const blob = res.data
      const reader = new FileReader()
      reader.readAsDataURL(blob)
      reader.onload = (e) => {
        const a = document.createElement('a')
        a.download = `現金流檔案`
        a.href = e.target.result
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
      }
    })
複製程式碼

相關文章