自学内容网 自学内容网

Java实现文件上传功能

目录

1、准备工作

2、注意事项

3、jsp页面代码

4、Servlet

5、注册Servlet


1、准备工作

导入依赖:commons-fileupload和commons-io

2、注意事项

        ①为保证服务器安全,上传文件应该放在外界无法直接访问的目录下,比如WEB-INF目录下

        ②为防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名(时间戳、uuid)

        ③要限制上传文件的最大值

        ④可以限制上传文件的类型,在收到上传文件名时,判断后缀名是否合法

3、jsp页面代码

注意:form表单要加上 enctype="multipart/form-data"

           并且method一定是post,因为get有大小限制

<html>
<body>

<form action="${pageContext.request.contextPath}/upload.do" method="post" enctype="multipart/form-data">
    上传用户:<input type="text" name="username"><br/>
    <p><input type="file" name="file1"></p>
    <p><input type="file" name="file2"></p>

    <p><input type="submit"> | <input type="reset"></p>
</form>


</body>
</html>

4、Servlet

 //判断上传的文件是普通表单,还是带文件的表单
        if(!ServletFileUpload.isMultipartContent(req)){
            return;//终止方法运行,说明这是一个普通表单,直接返回
        }

        try {
        //创建上传文件袋保存路径,建议在WEB-INF路径下,安全,用户无法直接访问上传的文件
        String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
        File uploadFile = new File(uploadPath);
        if(!uploadFile.exists()){
            uploadFile.mkdir();//创建这个目录
        }

        //缓存,临时文件
        //临时路径,假如文件超过了预期的大小。我们就把他放到一个临时文件中,过几天自动删除,或者提醒用户转存为永久
        String tmpPath = this.getServletContext().getRealPath("/WEB-INF/tmp");
        File tmpFile = new File(tmpPath);
        if(!tmpFile.exists()){
            tmpFile.mkdir();//创建这个临时目录
        }

1、创建DiskFileItemFactory对象

//处理上传的文件,一般都需要通过流来获取,我们可以使用req.getInputStream(),原生态的文件上传流获取,十分麻烦
        //建议使用Apache的文件上传组件来实现,common-fileupload,他需要依赖于commons-io组件

        //1、创建DiskFileItemFactory对象:处理文件上传路径或者大小限制的
        DiskFileItemFactory factory = new DiskFileItemFactory();

2、 获取ServletFileUpload

//2、获取ServletFileupload:监听文件上传进度、处理乱码问题、设置单个文件的最大值、设置总共能够上传文件的大小
        ServletFileUpload upload = new ServletFileUpload();

3、处理上传的文件

//3、处理上传的文件
        //把前端请求解析,封装成一个FileItem对象
            List<FileItem> fileItems = upload.parseRequest(req);
            for (FileItem fileItem : fileItems) {
                //判断上传的文件是普通表单,还是带文件的表单
                if(fileItem.isFormField()){
                    //普通表单
                    String name = fileItem.getFieldName();
                    String value = fileItem.getString("UTF-8");
                    System.out.println(name+":"+value);
                }else{//文件

                    //=========================处理文件============================//

                    //拿到文件名字
                    String uploadFileName = fileItem.getFieldName();
                    System.out.println("上传的文件名:"+uploadFileName);
                    //可能存在文件名不合法的情况
                    if(uploadFileName.trim().equals("") || uploadFileName==null){
                        continue;
                    }
                    //获取上传的文件名
                    String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
                    //获取文件的后缀名
                    String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);

                    //可以使用uuid保证文件名唯一
                    //UUID.randomUUID(),随机生成一个唯一的通用码
                    String uuidPath = UUID.randomUUID().toString();

                    //=========================存放地址============================//
                    String realPath = uploadPath+"/"+uuidPath;
                    //给每个文件创建一个对应的文件夹
                    File realPathFile = new File(realPath);
                    if(!realPathFile.exists()){
                        realPathFile.mkdir();
                    }

                    //=========================文件传输============================//
                    //获得文件上传的流
                    InputStream inputStream = fileItem.getInputStream();
                    //创建一个文件输出流
                    FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName);

                    //创建一个缓冲区
                    byte[] buffer = new byte[1024*1024];

                    //判断是否读取完毕
                    int len = 0;
                    //如果大于0,说明还存在数据
                    while((len = inputStream.read(buffer))>0){
                        fos.write(buffer,0,len);
                    }

                    //关闭流
                    fos.close();
                    inputStream.close();

                    //上传成功,清除临时文件
                    fileItem.delete();
                }
            }
        } catch (FileUploadException e) {
            throw new RuntimeException(e);
        }

 

5、注册Servlet


原文地址:https://blog.csdn.net/supercool7/article/details/143061472

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!