前端下载springboot后端服务器上的文件

由于项目原因前端页面和后端不在一个服务器上,因此想要从页面下载文件后端服务器保存的文件比较麻烦。
本篇文章参考了

https://blog.csdn.net/dkbnull/article/details/88858717

具体如下:

新建服务类

import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

@Service
public class LogService {
    public void logDownload(String name, HttpServletResponse response) throws Exception {
        File file = new File("D:\***\***" + "\\" + name);//后端服务器上存储的文件路径
        if (!file.exists()) {
        	System.out.println("不存在");
        	return;
        }
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(name, "UTF-8"));//URLEncoder.encode让下载的文件名不会是乱码
        byte[] buffer = new byte[1024];
        try (FileInputStream fis = new FileInputStream(file);
        		BufferedInputStream bis = new BufferedInputStream(fis)) {
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        }
    }
}

新建控制类

import team.lhc.cms.service.impl.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
@Scope("prototype")
public class LogController {

    @Autowired
    private LogService logService;

    //name是文件名,从前端获取
    @GetMapping(value = "/download/{name}")
    public void logDownload(@PathVariable String name, HttpServletResponse response) throws Exception {
        logService.logDownload(name, response);
    }
}

前端访问

<a href= 'http://服务器ip:端口号port/download/" +带后缀文件名var+ "'>下载a>

成功

你可能感兴趣的:(web,前端,spring,boot,服务器)