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.apachemons.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 = Logger(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 = "";
    //要下载的⽂件地址可以通过形参传进来
    String filepath = "f:/svs/" + fileName;
    OutputStream os = null;
    InputStream is = null;
springframework jar包下载    try {
      // 取得输出流
      os = OutputStream();
      // 清空输出流
      set();
      res.setContentType("application/x-download;charset=GBK");
      res.setHeader("Content-Disposition",
        "attachment;filename=" + new Bytes("utf-8"), "iso-8859-1"));
      // 读取流
      File f = new File(filepath);
      is = new FileInputStream(f);
      if (is == null) {
        reMap.put("msg", "下载附件失败");
      }
      // 复制
      py(is, OutputStream());
        OutputStream().flush();
      } catch (IOException e) {
        reMap.put("msg", "下载附件失败,error:" + e.getMessage());
      }
      // ⽂件的关闭放在finally中
      finally {
        try {
          if (is != null) {
            is.close();
          }
        } catch (IOException e) {
          (e.toString());
        }
        try {
          if (os != null) {
            os.close();
          }
        } catch (IOException e) {
          (e.toString());
        }
      }
      String str = JsonUtil.map2Json(reMap);      return str;
    }
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。