标签:启动 load pre osi write 操作 turn file head
SpringMVC 配置和依赖:https://www.cnblogs.com/pojo/p/14352800.html
注意:restFul 风格一般会把文件后缀名截取掉, 加上 :.+
来保留文件后缀名
package com.pro.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
@RestController
public class FileController {
// 使用restFul风格一般会把文件后缀名截取掉, 加上:.+ 来保留文件后缀名
@RequestMapping(value = "/download/{fileName:.+}")
public String download(@PathVariable String fileName, HttpServletResponse response, HttpServletRequest request) throws Exception {
System.out.println("download --> " + fileName);
//要下载的图片地址
String path = request.getServletContext().getRealPath("/upload");
//1、设置response 响应头
response.reset(); //设置页面不缓存,清空buffer
response.setCharacterEncoding("UTF-8"); //字符编码
response.setContentType("multipart/form-data"); //二进制传输数据
//设置响应头
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
File file = new File(path, fileName);
//2、 读取文件--输入流
InputStream input = new FileInputStream(file);
//3、 写出文件--输出流
OutputStream out = response.getOutputStream();
//4、执行 写出操作
byte[] buff = new byte[1024];
int index = 0;
while ((index = input.read(buff)) != -1) {
out.write(buff, 0, index);
out.flush();
}
// 关闭流
out.close();
input.close();
return null;
}
}
启动项目访问:http://localhost:8080/download/xxx.xx
我的项目中有一个 aa.pdf 的文件, 就直接访问
http://localhost:8080/download/aa.pdf
SpringMVC 使用RestFul风格实现简单的文件下载
标签:启动 load pre osi write 操作 turn file head
原文地址:https://www.cnblogs.com/pojo/p/14352894.html