- 现在大部分的业务都是需要通过后端下载一些模板,又或者在线浏览的,比例word,excel,pdf文件,都是需要下载,所以这里我也是遇到了,本来是在前端写一个链接,直接下载的,但是以防万一,可以通过后端接口对文档进行下载,下面给出代码例子
- 这里就写一个controller方法,就没有对他进行二次封装了,完全是copy下来的,如果有人看不习惯,可以对他进行二次封装,把他封装成一个工具类
package com.ruoyi.web.controller.ucase;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;
@RestController
@RequestMapping("/ucase/download")
@Slf4j
public class UcasePubController {
private static final String FIXED_PATH = "static/documentation/";
private static final String USER_AGENT_MSIE = "MSIE";
private static final String USER_AGENT_TRIDENT = "Trident";
@RequestMapping("/template")
@ResponseBody
public void downloadTemplate(@RequestParam Map<String, String> params, HttpServletResponse response, HttpServletRequest request) throws IOException {
log.debug("DownloadController{}==>downloadTemplate()");
InputStream inputStream = null;
OutputStream os = null;
try {
String path = Thread.currentThread().getContextClassLoader()
.getResource("").getPath() + FIXED_PATH + params.get("fileName");
inputStream = new FileInputStream(new File(path));
String filename = params.get("fileName");
String userAgent = request.getHeader("User-Agent");
if (userAgent.contains(USER_AGENT_MSIE) || userAgent.contains(USER_AGENT_TRIDENT)) {
filename = java.net.URLEncoder.encode(filename, "UTF-8");
} else {
filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
}
response.addHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", filename));
response.setContentType("multipart/form-data");
response.setCharacterEncoding("UTF-8");
os = response.getOutputStream();
byte[] b = new byte[2048];
int len;
while ((len = inputStream.read(b)) > 0) {
os.write(b, 0, len);
}
} catch (Exception e) {
log.error(e.getMessage());
} finally {
if (os != null) {
try {
os.close();
} catch (Exception e) {
log.error(e.getMessage());
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
log.error(e.getMessage());
}
}
}
}
}
- 把文件放在本地的静态资源目录下
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ef7925c6cd97fe22b3f5c47933a1ef71.png)
- 通过访问本地链接就可以进行访问了:http://localhost:9999/122/ucase/download/template?fileName=document.docx 参数是你的文件名
- 如图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/553da7775117e5bed6cb1a5ec5f5e32a.png)
- 后面我会自己把他封装成一个工具类