上传文件与读取文件列表以及创建文件

1、亲测能使用的:

https://www.cnblogs.com/biehongli/p/6502390.html

还没测试的:

https://www.cnblogs.com/hanyuan/archive/2012/06/09/upload.html

2、测试过程:

jsp页面:fileupload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传页面</title>
</head>
<body>
<script type="text/javascript">
    alert("${info}");
</script>

<!-- 上传文件是上传到服务器上,而保存到数据库是文件名 -->
<!-- 上传文件是以文件转换为二进制流的形式上传的 -->
<!-- enctype="multipart/form-data"需要设置在form里面,否则无法提交文件 -->
<form action="upload" method="post" enctype="multipart/form-data">
    <table>
        <tr>
            <td></td>
            <td><h1>文件上传</h1></td>
        </tr>
        <tr>
            <td>文件描述:</td>
            <td><input type="text" name="desc"/></td>
        </tr>
        <tr>
            <td>上传文件:</td>
            <td><input type="file" name="file"/></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="上传文件"/></td>
        </tr>
    </table>
</form>
</body>
</html>

servlet后台:UploadSpotImgServlet.java

package servlet;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/** 
* @author BieHongLi 
* @version 创建时间:2017年3月4日 下午5:29:03 
* 注意:上传文件必须添加@MultipartConfig()可以设置上传文件的大小
*/
@WebServlet("/upload")
@MultipartConfig
public class UploadSpotImgServlet extends HttpServlet{

    
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        try {
            //获取文件描述信息
            String desc=request.getParameter("desc");
            //获取上传的文件
            Part part=request.getPart("file");
            //获取请求的信息
            String name=part.getHeader("content-disposition");
            //System.out.println(name);//测试使用
            //System.out.println(desc);//
            
            //获取上传文件的目录
            String root=request.getServletContext().getRealPath("/upload");
            System.out.println("测试上传文件的路径:"+root);
            
            //获取文件的后缀
            String str=name.substring(name.lastIndexOf("."), name.length()-1);
            System.out.println("测试获取文件的后缀:"+str);
            
            //生成一个新的文件名,不重复,数据库存储的就是这个文件名,不重复的
            String filename=root+"\"+UUID.randomUUID().toString()+str;
            System.out.println("测试产生新的文件名:"+filename);
            
            //上传文件到指定目录,不想上传文件就不调用这个
            part.write(filename);
            
            request.setAttribute("info", "上传文件成功");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("info", "上传文件失败");
        }
        
        request.getRequestDispatcher("/fileupload.jsp").forward(request, response);
    }
    
}

测试结果:

3、下载文件:

 4、创建文件夹:【结合前后实现6提到的功能】

首先在jsp种增减name为uid的表单

然后,创建5的类

再然后改写servlet类为:

package servlet;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import test.utils.ReadFile;

/** 
* @author BieHongLi 
* @version 创建时间:2017年3月4日 下午5:29:03 
* 注意:上传文件必须添加@MultipartConfig()可以设置上传文件的大小
*/
@WebServlet("/upload")
@MultipartConfig
public class UploadSpotImgServlet extends HttpServlet{

    
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        try {
            //获取文件描述信息
            String desc=request.getParameter("desc");
            //获取上传的文件
            Part part=request.getPart("file");
            //获取请求的信息
            String name=part.getHeader("content-disposition");
            //System.out.println(name);//测试使用
            //System.out.println(desc);//
            
            //获取上传文件的根目录
            String root=request.getServletContext().getRealPath("/upload");
            //获取用户id,并以id创建文件夹
            String uid = request.getParameter("uid");
            String userRoot = createFile(root+"\"+uid);
            System.out.println("用户cisco的"+"测试上传文件的路径:"+userRoot);
            
            //获取文件的后缀
            String str=name.substring(name.lastIndexOf("."), name.length()-1);
            System.out.println("测试获取文件的后缀:"+str);
            
            //生成一个新的文件名,不重复,数据库存储的就是这个文件名,不重复的
            //生成用户的一个新的文件名
            String fileuser = userRoot+"\"+UUID.randomUUID().toString()+str;
            System.out.println("测试产生新的文件名用户文件:"+fileuser);
            
            //上传文件到指定目录,不想上传文件就不调用这个
            part.write(fileuser);
            
            //获取文件夹下的所有文件名
            ReadFile.readfile(userRoot);
            request.setAttribute("info", "上传文件成功");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("info", "上传文件失败");
        }
        
        request.getRequestDispatcher("/fileupload.jsp").forward(request, response);
    }
    /**
     * @see FileName是创建文件夹,请以用户id为文件夹
     * @param FileName
     */
    protected String createFile(String FileName) {
        File file=new File(FileName);
        if(!file.exists()){//如果文件夹不存在
            file.mkdir();//创建文件夹
        }
        //返回文件夹的名字
        return FileName;
    }
}

5、读取文件夹下的所有文件名:ReadFile.java

package test.utils;
import java.io.FileNotFoundException;

import java.io.IOException;
import java.io.File;

public class ReadFile {
        public ReadFile() {
        }
        /**
         * 读取某个文件夹下的所有文件
         */
        public static boolean readfile(String filepath) throws FileNotFoundException, IOException {
                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]);
                                        if (!readfile.isDirectory()) {
                                                System.out.println("path=" + readfile.getPath());
                                                System.out.println("absolutepath="
                                                                + readfile.getAbsolutePath());
                                                System.out.println("name=" + readfile.getName());

                                        } else if (readfile.isDirectory()) {
                                                readfile(filepath + "\" + filelist[i]);
                                        }
                                }

                        }

                } catch (FileNotFoundException e) {
                        System.out.println("readfile()   Exception:" + e.getMessage());
                }
                return true;
        }

        /**
         * 删除某个文件夹下的所有文件夹和文件
         */
        
        
        /*public static boolean deletefile(String delpath)
                        throws FileNotFoundException, IOException {
                try {

                        File file = new File(delpath);
                        if (!file.isDirectory()) {
                                System.out.println("1");
                                file.delete();
                        } else if (file.isDirectory()) {
                                System.out.println("2");
                                String[] filelist = file.list();
                                for (int i = 0; i < filelist.length; i++) {
                                        File delfile = new File(delpath + "\" + filelist[i]);
                                        if (!delfile.isDirectory()) {
                                                System.out.println("path=" + delfile.getPath());
                                                System.out.println("absolutepath="
                                                                + delfile.getAbsolutePath());
                                                System.out.println("name=" + delfile.getName());
                                                delfile.delete();
                                                System.out.println("删除文件成功");
                                        } else if (delfile.isDirectory()) {
                                                deletefile(delpath + "\" + filelist[i]);
                                        }
                                }
                                file.delete();

                        }

                } catch (FileNotFoundException e) {
                        System.out.println("deletefile()   Exception:" + e.getMessage());
                }
                return true;
        }*/
        
        public static void main(String[] args) {
                try {
                        readfile("e:/videos");
                        // deletefile("D:/file");
                } catch (FileNotFoundException ex) {
                } catch (IOException ex) {
                }
                System.out.println("ok");
        }

}

6、结合以上知识点:

完成servlet实现根据id创建文件夹,然后实现文件上传,最后实现读取文件夹下所有的文件名。

jsp->servlet上传

servlet->jsp显示

最终效果:

原文地址:https://www.cnblogs.com/ciscolee/p/11276850.html