SpringBoot+Axios 下载文件接口

额…毕竟本人不是专职做后台的,因此这里只是做一个SpringBoot接口代码笔记。
以下为源码:
后台Controller

package org.csu.drugcombserver.controller;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.csu.drugcombserver.core.BaseController;
import org.springframework.core.io.ResourceLoader;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@Validated
@RequestMapping("/download")
public class DownloadController extends BaseController {
    @Resource
    private ResourceLoader resourceLoader;
    private final static String[] FILE_NAMES = {"combination_bliss.csv",
            "integration.csv",
            "cell_line.csv",
            "drug_chemical_info.csv",
            "9606.protein_chemical.links.detailed.v5.0.tsv",
            "9606.protein.links.v11.0.txt"};

    @RequestMapping("/{index}")
    public void getDrugProteinLinks(HttpServletRequest request, HttpServletResponse response,@PathVariable("index") Integer index){
        String fileName = FILE_NAMES[index];
        InputStream inputStream = null;
        ServletOutputStream servletOutputStream = null;
        try {
            String path = "source" + File.separator + fileName;
            org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:"+path);
            response.setContentType("application/octet-stream");
            response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.addHeader("Pragma", "no-cache");

            inputStream = resource.getInputStream();
            servletOutputStream = response.getOutputStream();
            IOUtils.copy(inputStream, servletOutputStream);
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (servletOutputStream != null) {
                    servletOutputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                System.gc();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

需要注意的是方法中参数的位置,我之前就是把PathVariable注解放在第一个形参位置,所以response对象没办法传回流导致下载失败。

前端代码:

      downloadFileByIndex(index).then(res => { //res为axios请求返回的未被本地代码处理过的对象
        const url = window.URL.createObjectURL(new Blob([res.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', `${fileName}`)
        document.body.appendChild(link)
        link.click()
      })

你可能感兴趣的:(前端杂事,Java)