问题描述:在项目实训中要求实现下载文件功能
第一步:从后端获取文件并展示在页面上
前端代码就是请求接口,获取数据,展示数据
/*
从后端获取文件名展示在页面上,并且将文件名与url字符串拼接,组成真正的文件地址供点击下载
*/
async getDataFromBack(){
// const user = this.toStr(localStorage.getItem("user"))
let user ="student"
const res = await this.$http.post("http://121.4.96.102:8080/Test1/download2",{user})
if (res.status==200) {
console.log(res.data)
this.files = res.data //files 保存文件名
this.urls = JSON.parse(JSON.stringify(res.data))
for (let i = 0; i < this.urls.length; i++) {
this.urls[i] = this.href + decodeURI(this.urls[i]) //拼接形成地址
let object = {}
object.url = this.urls[i]
object.filename = this.files[i]
console.log(object.url)
this.icon[i] = matchType(object.filename)
this.file.push(object)
}
}
},
后端,
/*
方法参数 filepath,文件地址 name ,文件名
方法功能 从指定的文件地址中去读取包含name的文件 ,返回文件名组成的list
*/
public List<String> readfile(String filepath, String name) throws FileNotFoundException, IOException {
List<String> list = new ArrayList<>();
String encoding = System.getProperty("file.encoding");
try {
File file = new File(filepath);
if (!file.isDirectory()) {
System.out.println("文件");
System.out.println("path=" + file.getPath());
System.out.println("absolutepath=" + file.getAbsolutePath());
System.out.println("name=" + file.getName());
} else if (file.isDirectory()) {
System.out.println("文件夹");
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File readfile = new File(filepath + "/" + filelist[i]);
// File readfile = new File(filepath + "\\" + filelist[i]);
if (!readfile.isDirectory()) {
if (readfile.getName().contains(name)) {
// list.add(readfile.getName());
String filename = readfile.getName();
list.add(filename);
System.out.println(readfile.getName());
}
} else if (readfile.isDirectory()) {
readfile(filepath + "/" + filelist[i], "");
readfile(filepath + "\\" + filelist[i], "");
}
}
}
} catch (FileNotFoundException e) {
System.out.println("readfile() Exception:" + e.getMessage());
}
return list;
}
以老师访问为例,
public synchronized void service(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", " Origin, X-Requested-With, Content-Type, Accept");
response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
response.setHeader("X-Powered-By", " 3.2.1");
// 内容类型:如果是post请求必须指定这个属性
response.setHeader("Content-Type", "application/json;charset=utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("application/x-msdownload");
PrintWriter out = response.getWriter();
String str = getRequestPayload(request); //以字符串形式 获取前端传递的数据
SQLiteManager manager = new SQLiteManager(); //数据库的操作工具(自己写的)
if (str != null && str.length() != 0) {
System.out.println(str);
JSONObject jsonObject = JSON.parseObject(str);
String user = jsonObject.getString("user"); //获取请求者的身份,老师和学生下载的东西是存放在不同文件夹中的
System.out.println(user);
// 老师页面
if (!user.equals("student")) {
String folder = "upload";
// String name = manager.getTeacherName(user);
// System.out.println(name);
try {
// String filepath = request.getSession().getServletContext().getRealPath("") + "\\upload";
String filepath = "/usr/local/tomcat/apache-tomcat-7.0.107/webapps/Test1/upload/";
System.out.println(filepath);
// List<String> list = readfile(filepath + File.separator + folder, user);
List<String> list = readfile(filepath, "_" + user);
String res = JSON.toJSONString(list); //将文件名list转化为json字符串 发给前端
out.write(res);
out.close();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getClass().getName() + ": " + e.getMessage());
}
第二步 前端直接点击下载就可以下载了
之前提到过 后端传递过去的文件名,会在前端被拼接成一个地址 比如
https://127.0.0.1:8080/project/download/1.txt
那么当前端点击这个超链接时,网页就会去访问你project目录下的download文件夹里有没有1.txt ,如果有它自动就会下载。