• 文件上传功能实现代码


    单一文件上传:
    一、前台 uploadFile.jsp
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
     
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
     
        <title>My JSP 'uploadFile.jsp' starting page</title>
     
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <meta http-equiv="ContentType" content="text/html;charset=UTF-8">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
     
      </head>
     
      <body>
          <form action="upload.action" method="post" enctype="multipart/form-data">
            <input type="file" name="myfile" />
              <input type="submit" name="upload" value="上传" />
          </form>
     
      </body>
    </html>
    二、后台 uploadFile.jsp
    package com.zhaoran.controller;
     
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
     
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;
     
    public class UploadServlet extends HttpServlet{
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doPost(req, resp);
        }
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.setCharacterEncoding("UTF-8");
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html;charset=UTF-8");
            Part part=req.getPart("myfile");
            String filename=getFileName(part);
            writeTo(filename,part);
            req.setAttribute("msg", "文件上传成功");
            req.getRequestDispatcher("common/success.jsp").forward(req, resp);
        }
        private void writeTo(String filename, Part part) throws IOException {
            InputStream inputStream=part.getInputStream();
            OutputStream outputStream=new FileOutputStream("e://"+filename);
            byte[] buff=new byte[1024];
            int len=-1;
            while((len=inputStream.read(buff))!=-1){
                outputStream.write(buff, 0, len);
            }
            outputStream.close();
            inputStream.close();
        }
        private String getFileName(Part part) {
            //String header=part.getHeader("Content-Disposition");
            String header=part.getHeader("Content-Disposition");
            System.out.println(header);
            String filename=header.substring(header.indexOf("filename="")+10,header.lastIndexOf("""));
            System.out.println(filename);
            return filename;
        }
    }
    三、配置文件 web.xml
    <?xml version="1.0" encoding="UTF-8"?>
      <display-name>login</display-name>
     
      <servlet>
          <servlet-name>loginServlet</servlet-name>
          <servlet-class>com.zhaoran.controller.LoginServlet</servlet-class>
      </servlet>
      <servlet-mapping>
          <servlet-name>loginServlet</servlet-name>
          <url-pattern>/login.action</url-pattern>
      </servlet-mapping>
      <servlet>
          <servlet-name>uploadServlet</servlet-name>
          <multipart-config></multipart-config>
          <servlet-class>com.zhaoran.controller.UploadServlet</servlet-class>
      </servlet>
      <servlet-mapping>
          <servlet-name>uploadServlet</servlet-name>
          <url-pattern>/upload.action</url-pattern>
      </servlet-mapping>
      <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
      </welcome-file-list>
    </web-app>
     
     
    文件的批量上传:
    一、前台页面
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
     
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
     
        <title>My JSP 'uploadFile.jsp' starting page</title>
     
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <meta http-equiv="ContentType" content="text/html;charset=UTF-8">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
     
      </head>
     
      <body>
    <!-- 文件上传时,enctype需设置为multipart/form-data-->
          <form action="upload.action" method="post" enctype="multipart/form-data">
            <input type="file" name="myfile" />
            <br />
              <input type="submit" name="upload" value="上传" />
          </form>
          <hr />
          <form action="upload2.action" method="post" enctype="multipart/form-data">
            <input type="file" name="myfile" />
            <br />
              <input type="submit" name="upload" value="上传" />
          </form>
          <hr />
          <form action="upload3.action" method="post" enctype="multipart/form-data">
            文件一:<input type="file" name="myfile1" />
            <br />
            文件二:<input type="file" name="myfile2" />
            <br />
            文件三:<input type="file" name="myfile3" />
            <br />
              <input type="submit" name="upload" value="上传" />
          </form>
      </body>
    </html>
     
    二、后台servlet   UploadServlet3.java
    package com.zhaoran.controller;
     
    import java.io.IOException;
     
    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;
    //采用注解方式配置servlet,文件上传中@MultipartConfig必不可少
    @MultipartConfig(location="e://")
    @WebServlet("/upload3.action")
    public class UploadServlet3 extends HttpServlet {
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.setCharacterEncoding("UTF-8");
            for(Part part:req.getParts()){
    //            System.out.println(part.getName());
                if(part.getName().startsWith("myfile")){
                    String filename=getFileName(part);
    //                System.out.println(filename);
                    part.write(filename);
                }
            }
            req.setAttribute("msg", "文件批量上传成功");
            req.getRequestDispatcher("common/success.jsp").forward(req, resp);
            return;
        }
        private String getFileName(Part part) {
            String header=part.getHeader("Content-Disposition");//Content-Disposition
            String filename=header.substring(header.indexOf("filename="")+10, header.lastIndexOf("""));
            return filename;
        }
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doPost(req, resp);
        }
    }
    三、采用注解方式,未使用配置文件web.xml
  • 相关阅读:
    数据库设计步骤 java程序员
    (1) 语法结构 java程序员
    (3)JavaScript学习笔记 函数、对象、数组 java程序员
    JavaScript 学习计划 java程序员
    (5)JavaScript学习笔记 变量 java程序员
    (2) 数据类型、值 及 字符串 java程序员
    (4)JavaScript学习笔记 数据类型和值(续) java程序员
    J2EE、J2SE、J2ME是什么意思? java程序员
    80端口(该端口是Tomcat的监听端口)已经被其他程序占用 java程序员
    (17) string 和 stringbuilder java程序员
  • 原文地址:https://www.cnblogs.com/zhaoran8775/p/5521480.html
Copyright © 2020-2023  润新知