• 文件上传功能的实现


    一:文件上传功能

    先要在在index.jsp的界面上初始化一个表单。

    代码如下:


    <body>
    <form enctype="multipart/form-data" action="<%=path%>/1.jsp" method="post">
    姓名:<input type="text" name="username"/>
    选择文件:<input type="file" name="myfile"/>
    <input type="submit" value="提交"/>
    </form>

    :enctype=多部分的表单数据,并且如果form表单的属性中多了enctype="multipart/form-data",是不能使用request.getParameter(name属性的)

    在WEB-ROOT的根目录下创建一个1.jsp,实现文件上传功能!
    代码如下:

    <%@page import="java.io.File"%>
    <%@page import="org.apache.commons.fileupload.FileItem"%>
    <%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
    <%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    //判定request请求的类型
    request.setCharacterEncoding("utf-8");
    boolean flag= ServletFileUpload.isMultipartContent(request);
    if(flag)
    {
    DiskFileItemFactory factory=new DiskFileItemFactory();
    //找到一个解析器,解析请求中的各个项目
    ServletFileUpload upload=new ServletFileUpload(factory);//解析器的创建
    List<FileItem> list=upload.parseRequest(request);//使用解析器解析请求的数据
    Iterator<FileItem> myitor= list.iterator();//自动迭代的功能
    while(myitor.hasNext())
    {
    FileItem item=myitor.next();
    if(item!=null)
    {
    //判断FileItem对象封装的数据类型,文件表单或普通表单字段
    if(item.isFormField())//普通表单
    {
    String name= item.getFieldName();//获取表单的name属性
    if(name.equals("username"))
    {
    out.print(item.getString("utf-8"));
    }
    }
    else
    {
    String name=item.getName();//获得文件名
    out.print(name);
    String path="/WEB-INF/upload/";//相对路径名
    String path2=this.getServletContext().getRealPath(path);//通过相对路径名来获得绝对路径名
    out.print(path2);
    File file=new File(name);
    File uploadpath=new File(path2,file.getName());
    item.write(uploadpath);//向该路径写入文件
    out.print("上传成功");
    }
    }
    }
    }

  • 相关阅读:
    MySql8安装使用中的一些注意
    如何在CentOS 8主机上安装Nginx Web服务器
    centos安装sqlserver
    VSCode快捷键
    C#中的委托
    Winform加载loading界面
    JayRock的一些用法:json and json rpc for .Net
    winform picturebox控件 定时让图片轮播
    sql server创建存储过程
    ftp上传单一文件示例
  • 原文地址:https://www.cnblogs.com/hero96/p/5639470.html
Copyright © 2020-2023  润新知