ajax+springboot获取遍历文件夹

8 篇文章 0 订阅
22 篇文章 0 订阅

思路

老办法ajax前后端互传参数,前端表单提交需要遍历哪个父文件夹,后端遍历父文件夹并发送json数组给js,js接收后显示在页面上
两个不太好的地方
sp1:判断对象是文件夹还是文件,这里采用了正则表达式判断文件名,如果只有数字字母下划线则判断为文件夹(文件带后缀.dov),所以文件夹最好是英文的~
sp2:输入文件夹名字时由于要传给ajax,获取input输入内容没有用表单而 是document.getElementById(“foldername”).value函数,需要额外设置一个按钮使其提交

前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>

    输入文件夹名称:<input  type="text" id="foldername" value="这是内容" ><br>

    <button onclick="textchange()">提交文本</button>
<div id="txtHint"><b>所有文件和文件夹将显示在此处</b></div>
<button onclick="showUser('q')">按钮</button>

    <script>
        function getHsonLength(json){
            var jsonLength=0;
            for (var i in json) {
                jsonLength++;
            }
            return jsonLength;
        }
        function isValid(str) { return /^\w+$/.test(str); }
        //var utext = document.getElementById("foldername");
        // var foldername1=document.getElementById("foldername").innerHTML
        function textchange(){

        var foldername1 = document.getElementById("foldername").value
       // alert(foldername1);
        return foldername1;
        }
        var count=1;
       // function showUser(str) {
        showUser=function (str){

            if(count==1)
            { str=textchange();}
           count=2;

           // alert(str);
            //str="01";
            if (str=="") {
                document.getElementById("txtHint").innerHTML="";
                return;
            }
            if (window.XMLHttpRequest) {
                // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
            } else { // code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function() {
                if (this.readyState==4 && this.status==200) {
                  //  document.getElementById("txtHint").innerHTML=this.responseText;
                    var data1 = JSON.parse(this.responseText);
                    for(var i=0;i<getHsonLength(data1);i++) {
                        var patt = new RegExp("");
                        // if (patt.test(data1[i].name) == false) {
                        if(isValid(data1[i].name)){
                            //alert(data1[i].name);
                            document.write("子文件夹:")
                            //document.write("<br/>")
                         // document.write("<a href='#'>"+data1[i].name+"</a>")
                           var zi=str+"/"+data1[i].name;
                     //       alert(zi)
                            document.write("<button οnclick='showUser(&quot;"+zi+"&quot;);'>"+data1[i].name+"</button>")
                            document.write("<br/>")
                           // document.write("<br/>")
                        }
                        else{
                            document.write("文件:")
                            // document.write("<br/>")
                            document.write("<a href='#'>"+data1[i].name+"</a>")
                            document.write("<br/>")

                        }



                    }
                }
            }
            xmlhttp.open("GET","/j2eelist2?q="+str,true);
            xmlhttp.send();

        }
        //新的

    </script>

</body>
</html>

后端

package com.documentstation.demo.controller;




import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@WebServlet(name = "j2eelist2", urlPatterns = "/j2eelist2")
public class j2eelist2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       String fn=request.getParameter("q");
        // 获取download目录下所有的文件名(放置下载文件的文件目录)
        //     String realPath = getServletContext().getRealPath("temp1");
        String realPath ="D:/"+fn+"/";
        File file = new File(realPath);
        File[] list = file.listFiles();
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        JSONArray jsonArray = new JSONArray();
         JSONObject jsonObj = new JSONObject();
        response.setContentType("text/json;charset=utf-8");
        // 实例化输出流对象
        PrintWriter out = response.getWriter();
        for (File f : list) {
            String name = f.getName();
            // 对内容使用url编码 编码之后的内容ie可以解析
            String encodeName = URLEncoder.encode(name, "utf-8");
            System.out.println(name);
            //  response.getWriter().write("<a href='http://192.168.1.107:8080/spring14/tool/" + name + "'>" + name + "</a><br/>");
           // response.getWriter().write("<img src=\"wenjian.png\" width=100px height=80px\">");
            jsonObj.put("name",name);
            //       jsonObj.put("url",rs.getString("url"));

             jsonArray.add(jsonObj); // 把对象放到数组里,容易遍历


        }

        out.println(jsonArray);
    }


上传文件/创建文件夹

(核心html代码)

<div class="row zhan"></div>
    <div class="row">
        <form method="post" action="/folder" enctype="multipart/form-data">
            输入文件夹名称:<input  type="text" name="foldername" ><br>
            <input type="submit" value="创建文件夹">
        </form>
    </div>
    <div class="row">
        <form method="post" action="/upload" enctype="multipart/form-data">
            <input  type="file" name="file" ><br>
            <input type="submit" value="提交">
        </form>
    </div>

uploadcontroller.java

package com.documentstation.demo.controller;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @Description
 * @Author sgl
 * @Date 2018-05-15 14:04
 */
@Controller
public class UploadController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

    @GetMapping("/upload")
    public String upload() {
        return "upload";
    }

    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "上传失败,请选择文件";
        }

        String fileName = file.getOriginalFilename();
       // String filePath = "C:/Users/17695/IdeaProjects/documentstation/src/main/webapp/tmp/";
        String filePath = "D:/uploadtest/";

        File dest = new File(filePath + fileName);
        try {
            file.transferTo(dest);
            LOGGER.info("上传成功");
            return "上传成功";
        } catch (IOException e) {
            LOGGER.error(e.toString(), e);
        }
        return "服务器维护,暂停上传功能,下载仍可正常使用!";
    }


}


folder.java

package com.documentstation.demo.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.io.File;

@Controller
public class folder {

    @ResponseBody
    @RequestMapping("folder")
    public static String hello(HttpServletRequest request){
        String foldername=request.getParameter("foldername");
        File file=new File("D:\\"+foldername);
        if(!file.exists()){//如果文件夹不存在
            file.mkdir();//创建文件夹
        }
        return "quick helloworld";
    }
}

  • 0
    点赞
  • 2
    收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:精致技术 设计师:CSDN官方博客 返回首页
评论

打赏作者

危笑qwq

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值