• 文件上传功能实现代码


    单一文件上传:
    一、前台 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
  • 相关阅读:
    二叉树
    oracle 查看某session的历史执行sql情况
    mongodb备份与恢复
    MongoDB数据库基本用法
    常见Oracle HINT的用法
    提高Oracle的WHERE语句性能一些原则
    javascript的类、委托、事件
    Swift数据类型简介(二)
    arcgis api 3.x for js 入门开发系列十七在线天地图、百度地图、高德地图(附源码下载)
    arcgis api 4.x for js之图层管理篇
  • 原文地址:https://www.cnblogs.com/zhaoran8775/p/5521480.html
Copyright © 2020-2023  润新知