1、需要在启动类设置@ServletComponentScan 这样才能扫描到我们创建的servlet
2、实现自己的Servlet
最常用的就是实现Servlet接口,或者直接集成HttpServlet。自己实现接口的形式要自己重写service方法,而集成HttpServlet的话一般直接重写doPost,doGet等方法实现自己的处理逻辑
3、使用注解@WebServlet(urlPatterns = "/index.do")实现注册servlet,并配置路径
服务器响应PDF流
设置响应头content-type=application/pdf,表示我们将返回一份 PDF 格式的文件
@WebServlet(urlPatterns = "/hello", loadOnStartup = 1)
public class Myservlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("application/pdf");
ServletOutputStream outputStream = resp.getOutputStream();
outputStream.write(read());
outputStream.flush();
outputStream.close();
}
private byte[] read() throws IOException {
FileInputStream inputStream = new FileInputStream("C:\\Users\\zz\\Documents\\SpringCloud Alibaba实战.pdf");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int read = inputStream.read(bytes);
while (read > 0) {
outputStream.write(bytes, 0, read);
read = inputStream.read(bytes);
}
byte[] res = outputStream.toByteArray();
outputStream.flush();
outputStream.close();
inputStream.close();
return res;
}
}
服务器响应图片流
设置响应头content-type=image/png,表示我们将返回一张 png 格式的图片
服务器响应json数据流
application/json
服务器响应html格式
text/html
纯文本
默认content-type=text/plain,纯文本,浏览器中会直接以文本形式展示出来。
下载doc文件
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
FileUtils.writeBytes("C:\\Users\\qqqq\\Downloads\\寺河煤qqqq诊断报.doc", response.getOutputStream());
这种情况,下载的文件没有后缀啊
response.setContentType("application/msword");
FileUtils.writeBytes("C:\\Users\\qqq\\Downloads\\寺河煤qqq断报.doc", response.getOutputStream());
这种写法,下载的是doc文件,但是名称是默认名称
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
String encode = URLEncoder.encode("我得文件.doc", StandardCharsets.UTF_8.toString());
String percentEncodedFileName = encode.replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment; filename="+percentEncodedFileName);
FileUtils.writeBytes("C:\\Users\\qqq\\Downloads\\寺qq报.doc", response.getOutputStream());
这种写法,能指定doc名称
输出json文字
// response.setStatus(200);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
// response.getWriter().print(JSON.toJSONString(AjaxResult.success("你好啊")));
byte[] bytes = JSON.toJSONString(AjaxResult.success("你好啊")).getBytes();
response.getOutputStream().write(bytes,0,bytes.length);
下载pdf文件
Content-Type: application/pdf
Content-Disposition: attachment; filename="document.pdf"
Content-Type: image/jpeg
Content-Disposition: attachment; filename="image.jpg"
当客户端收到这些头信息时,会根据 Content-Type
来决定如何处理或展示文件。如果是浏览器,它通常会提示用户下载该文件。
在 Vue 中,如果你想要触发浏览器的下载功能(例如下载一个文件)
可以通过创建一个隐藏的 <a>
标签并触发其 click
事件来模拟下载操作。
- 创建一个
<a>
标签并设置其href
属性为要下载的文件路径。- 设置
download
属性,这样浏览器会触发文件下载。- 使用 JavaScript 触发该
<a>
标签的点击事件。
<template>
<div>
<button @click="downloadFile">下载文件</button>
</div>
</template>
<script>
export default {
methods: {
downloadFile() {
// 创建一个临时的 <a> 元素
const link = document.createElement('a');
// 设置文件的下载地址
link.href = 'https://example.com/file-to-download.pdf';
// 设置下载的文件名(可选)
link.download = 'downloaded-file.pdf';
// 触发点击事件,开始下载
link.click();
// 清除临时创建的链接
link.remove();
}
}
}
</script>
解释
link.href
设置了你要下载的文件的 URL。link.download
设置了下载文件的名称。如果不设置,浏览器会使用 URL 的文件名作为默认名称。link.click()
通过编程方式模拟点击事件,从而触发下载。
处理 Blob 数据
如果你要下载的是动态生成的文件(如从后端返回的文件数据),你可以使用 Blob
对象来生成文件并下载:
<template>
<div>
<button @click="downloadBlobFile">下载Blob文件</button>
</div>
</template>
<script>
export default {
methods: {
downloadBlobFile() {
// 模拟生成一些文件内容,例如一个文本文件
const text = 'Hello, this is the content of the file!';
const blob = new Blob([text], { type: 'text/plain' });
// 创建一个临时的 <a> 元素
const link = document.createElement('a');
// 创建一个URL对象
const url = URL.createObjectURL(blob);
// 设置下载的文件名
link.download = 'example.txt';
// 设置 <a> 的 href 为 Blob URL
link.href = url;
// 触发点击事件,开始下载
link.click();
// 清理 Blob URL
URL.revokeObjectURL(url);
// 清除临时创建的链接
link.remove();
}
}
}
</script>
解释
- 使用
Blob
创建一个二进制大对象,其中可以包含文本、图片或其他文件内容。- 使用
URL.createObjectURL(blob)
生成一个可以下载的临时 URL。- 设置
link.href
为该 Blob URL 并触发下载。这样,你就可以轻松地在 Vue 中触发文件的下载操作了!
使用 Vue 下载文件
- 通过
axios
请求文件并下载
使用axios
来请求文件并触发浏览器下载操作。假设你有一个后端接口返回文件流,设置适当的Content-Type
,然后通过 JavaScript 创建一个下载链接。
import axios from 'axios';
export default {
methods: {
downloadFile() {
axios({
url: 'http://example.com/api/download', // 你的文件下载接口
method: 'GET',
responseType: 'blob', // 返回类型为 Blob
})
.then(response => {
const blob = response.data;
const link = document.createElement('a');
const url = window.URL.createObjectURL(blob);
// 设置下载文件名和 Content-Type
link.href = url;
link.download = 'downloaded-file.pdf'; // 根据实际文件设置名称
link.setAttribute('Content-Type', 'application/pdf'); // 设置合适的 MIME 类型
document.body.appendChild(link);
link.click();
// 下载后清理
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
})
.catch(error => {
console.error('Download error:', error);
});
}
}
}
解释
responseType: 'blob'
告诉axios
返回一个二进制流数据。- 使用
window.URL.createObjectURL(blob)
创建一个指向该文件的 URL。 - 通过
<a>
标签的download
属性触发浏览器下载文件,并通过Content-Type
设置文件类型。
注意
- 根据实际情况,你可能需要根据后端返回的文件类型动态设置
Content-Type
,例如判断返回的是 PDF、Excel 还是其他类型的文件,并设置相应的download
文件名和Content-Type
。 - 后端需要正确设置文件的响应头,特别是
Content-Disposition
(例如Content-Disposition: attachment; filename="filename.pdf"
),以指示浏览器进行下载。