栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

Java接收前端上传文件,保存文件到本地,并将相关信息存储如数据库,最后用JavaScript将上传文件信息在前端展示

Java接收前端上传文件,保存文件到本地,并将相关信息存储如数据库,最后用JavaScript将上传文件信息在前端展示

直接上运行效果


注意事项(代码较多,放在后面)
  1. 导入 .jar包 ,使用Maven时,不需要手动导入 jar包 ,在pom.xml文件中加入依赖即可,加入之后点击右侧Maven图标,并按刷新按钮,Maven会自动更新和下载jar包(如图)

  1. 有些需要本地导入的jar包,操作方法如下:
  •  将jar包导入Maven本地仓库,然后可以在项目中使用

 在cmd窗口中输入下面的代码,即可将jar包导入本地仓库

mvn install:install-file 
-Dfile=G:FileJavaTool_Filejarcommon-fileUpLoadcommons-fileupload-1.4.jar 
-DgroupId=RedMaple 
-DartifactId=FileUpLoad.sources 
-Dversion=1.0 
-Dpackaging=jar

Dfile 为绝对路径

DgroupId,DartifactId,Dversion 分别对应pom.xml文件中的groupId,artifactId,version

Dpacking=jar 照抄,注意D前面都有 - 号

成功后,就在pom.xml的 dependency中加入如下内容即可


      RedMaple
      Commons.lang3
      1.0
关于Java接收上传文件具体内容
  • 需要引入的依赖

    RedMaple
    FileUpLoad.sources
    1.0



   RedMaple
   Commons.Io
   1.0
// Servlet 文件上传
public class UploadServlet extends HttpServlet
{
    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws IOException, ServletException {
        res.setContentType("text/plain;charset=UTF-8");
        PrintWriter pw = res.getWriter();
        try{

            DiskFileItemFactory diskFactory = new DiskFileItemFactory();

            // threshold 极限、临界值,即硬盘缓存 1M
            diskFactory.setSizeThreshold(4 * 1024);

            // repository 贮藏室,即临时文件目录
            diskFactory.setRepository(new File("G:\File\Temp_File"));

            ServletFileUpload upload = new ServletFileUpload(diskFactory);

            // 设置允许上传的最大文件大小 4M
            upload.setSizeMax(4 * 1024 * 1024);

            // 解析HTTP请求消息头(得到请求参数的集合)
            List fileItems = upload.parseRequest(req);

            // 进行迭代
            Iterator iter = fileItems.iterator();
            while(iter.hasNext())
            {
                FileItem item = (FileItem)iter.next();
                
                // 判断是否是普通表单
                if(item.isFormField())
                {
                    // 是普通表单
                    System.out.println("处理表单内容 ...");
                    processFormField(item, pw);
                }else{
                    // 不是普通表单
                    System.out.println("处理上传的文件 ...");
                    processUploadFile(item, pw);
                }
            }
        }catch(Exception e){
            System.out.println("使用 fileupload 包时发生异常 ...");
            e.printStackTrace();
        }finally{
            pw.close();
        }
    }
    
    // 处理表单内容
    private void processFormField(FileItem item, PrintWriter pw) throws Exception {
        String name = item.getFieldName();    // 获取参数名称
        String value = item.getString();      // 获取值
    }

    // 处理上传的文件
    private void processUploadFile(FileItem item, PrintWriter pw) throws Exception {

        // 不同浏览器得到的getName()是不一样的,是否要加工再具体讨论
        // 有的是绝对路径有的是文件名
        String filename = item.getName();
        
        // 获取文件大小
        long fileSize = item.getSize();
        
        // 创建一个接收该文件的文件模板
        File uploadFile = new File("G:\File\Txt_File" + "/" + filename);

        //将文件读取并写入模板中
        item.write(uploadFile);
    }
}
用到的Gson类
  • 要用到的依赖

      com.google.code.gson
      gson
      2.8.3
// 将 filesArrayList对象 变为 Json字符串
Gson gson = new Gson();
json = gson.toJson(filesArrayList);

最后,使用了Maven的pom.xml 文件之后,似乎不需要WEB-INF文件夹下的lib文件夹来存放jar包了。(刚用Maven不久,只是猜测,有人会的话可以评论教教我) 


核心代码

接收并将文件信息存入数据库

// Servlet 文件上传
public class UploadServlet extends HttpServlet
{
    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws IOException, ServletException {

        res.setContentType("text/html;charset=utf-8");
        PrintWriter pw = res.getWriter();
        try{
            DiskFileItemFactory diskFactory = new DiskFileItemFactory();
            // threshold 极限、临界值,即硬盘缓存 1M
            diskFactory.setSizeThreshold(4 * 1024);
            // repository 贮藏室,即临时文件目录
            diskFactory.setRepository(new File("G:\File\Temp_File"));
            ServletFileUpload upload = new ServletFileUpload(diskFactory);
            // 设置允许上传的最大文件大小 1G
            upload.setSizeMax(1024 * 1024 * 1024);
            // 解析HTTP请求消息头
            List fileItems = upload.parseRequest(req);
            Iterator iter = fileItems.iterator();
            while(iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if(!item.isFormField()){
                    System.out.println("处理上传的文件 ...");
                    processUploadFile(item,pw,req,res);
                }
            }
        }catch(Exception e){
            System.out.println("使用 fileupload 包时发生异常 ...");
            e.printStackTrace();
        }finally {
            pw.close();
        }
    }// end doPost()

    // 处理上传的文件
    private void processUploadFile(FileItem item, PrintWriter pw,HttpServletRequest req
                ,HttpServletResponse res) throws Exception {
        // 此时的文件名包含了完整的路径,得注意加工一下
        String fileName = item.getName();
        int index = fileName.lastIndexOf(".");
        String extension = fileName.substring(index+1,fileName.length());
        long fileSize = item.getSize();
        String filePath = "G:\File\Temp_File" + "/" + fileName;
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String time = sdf.format(date);
        File uploadFile = new File(filePath);
        item.write(uploadFile);
        Files files = new Files(fileName,String.valueOf(fileSize),filePath,time);
        addFile(files);
        req.getRequestDispatcher("T03.jsp").forward(req,res);
    }

    private void addFile(Files files){
        Connection conn = Mysql.connection("filesys");
        String sql = "insert into file(filename,filesize,filepath,time) values(?,?,?,?);";
        PreparedStatement ps = Mysql.prepareStatement(conn,sql);
        Mysql.setString(ps,1,files.fileName);
        Mysql.setString(ps,2,files.fileSize);
        Mysql.setString(ps,3,files.filePath);
        Mysql.setString(ps,4,files.time);
        Mysql.executeUpdate(ps);
        Mysql.close(conn,ps);
    }
}

 读取数据,并将数据以Json格式发送给前端AJAX

public class GetDate extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException{
        String[] filesArrayList = new String[100];
        boolean flag = findFile(filesArrayList);
        String json = "{:}";
        if(flag){
            Gson gson = new Gson();
            json = gson.toJson(filesArrayList);
        }
        response.setContentType("text/html;charset=utf-8");
        PrintWriter pw = response.getWriter();
        pw.println(json);
    }

    private boolean findFile(String[] filesArrayList){
        boolean flag = false;
        Connection conn = Mysql.connection("filesys");
        String sql = "select * from file;";
        PreparedStatement ps = Mysql.prepareStatement(conn,sql);
        ResultSet rs = Mysql.executeQuery(ps);
        int i = 0;
        while(Mysql.next(rs)){
            String fileName = Mysql.getString(rs,"filename");
            String fileSize = Mysql.getString(rs,"filesize");
            String filePath = Mysql.getString(rs,"filepath");
            String time = Mysql.getString(rs,"time");
            Files files = new Files(fileName,fileSize,filePath,time);
            Gson gson = new Gson();
            filesArrayList[i++] = gson.toJson(files);
            flag = true;
        }
        Mysql.close(conn,ps);
        return flag;
    }
}

AJAX和JQuery联用,将文件信息在前端展示 

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false"%>


    
    
    
        table{
            margin-top:10px;
            border:1px black solid;
        }
        .tableTitle{
            width:150px;
            background-color: rgb(130, 113, 204);
            color:white;
            font-size:17px;
        }
        td{
            text-align:center;
            outline: 1px white solid;
            background-color: rgb(222,223,222);
        }
    


上传文件列表:
自动序列 文件名 扩展名 文件大小 文件路径 上传时间 备注说明

相关配置信息


    
      junit
      junit
      4.11
      test
    
    
    
      javax.servlet
      javax.servlet-api
      3.0.1
    
    
      javax.servlet.jsp
      jsp-api
      2.1
    
    
      RedMaple
      FileUpLoad
      1.0
    
    
      RedMaple
      FileUpLoad.sources
      1.0
    
    
      RedMaple
      Commons.Io
      1.0
    
    
      RedMaple
      Mysql
      1.0
    
    
      com.google.code.gson
      gson
      2.8.3
    
    
      RedMaple
      Commons.lang3
      1.0
    

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/329698.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号