Method of Fast Uploading File Based on JSP

  • 2021-07-18 08:45:08
  • OfStack

In this paper, an example is given to describe the method of uploading files quickly by JSP. Share it for your reference. The details are as follows:

Here, JSP does not use the third party library to realize the function of uploading files quickly

1. FileUpload. java:


package FileUpload;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import javax.servlet.ServletInputStream;
/**
 * 
 */
/**
 * @author Qch
 * 
 */
public class FileUpload
{
  ServletInputStream in=null;
  String fpath="C://";
  public FileUpload()
  {
    fpath="C://";
    in=null;
  }
  public void setInputStream(ServletInputStream in)
  {
    this.in=in;
  }
  public void setFpath(String p)
  {
    this.fpath=p;
  }
  public String getFpath()
  {
    return fpath;
  }
  public String getParameter()
  { 
    String r=null;
    try
    {
      r=getParameter(in);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return r;
  }
  public long getFileUpload()
  {
    long r=-1;
    try
    {
      r=getFileUpload(in,fpath);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return r;
  }
  public String getParameter(ServletInputStream in)//  Can only be extracted in sequence 
      throws Exception
  {
    int l = 0;
    byte[] b = new byte[1024];
    l = in.readLine(b, 0, b.length);//  Read the beginning character of the attribute, the name, the type of the attribute value, and the value of the attribute in turn 
    String si = new String(b);
    if (si.startsWith("----------------------------"))
    {//  Indicates that the read starts from the starter, otherwise it should be just after reading the file 1 Attributes, which should be read less at this time 1 Times 
      l = in.readLine(b, 0, b.length);
    }
    l = in.readLine(b, 0, b.length);
    l = in.readLine(b, 0, b.length);
    String value = new String(b, 0, l);
    return value;
  }
  public long getFileUpload(ServletInputStream in, String fpath)//  Need to provide input stream and storage path 
      throws Exception
  {
    // out.println(" File information :<br>");
    long begin = System.currentTimeMillis();//  Transfer time timing starts 
    int l = 0;
    byte[] b = new byte[1024];
    l = in.readLine(b, 0, b.length);
    String sign = new String(b, 0, l);// eg.-----------------------------7d9dd29630a34
    l = in.readLine(b, 0, b.length);
    String info = new String(b, 0, l);// eg.Content-Disposition:form-data;
    // name="file";
    l = in.readLine(b, 0, b.length);
    // String type=new
    // String(b,0,l);//eg.Content-Type:application/octet-stream( Program file )
    l = in.readLine(b, 0, b.length);
    // String nulll=new String(b,0,l);// This value should be empty 
    int nIndex = info.toLowerCase().indexOf("filename=\"");
    int nLastIndex = info.toLowerCase().indexOf("\"", nIndex + 10);
    String filepath = info.substring(nIndex + 10, nLastIndex);
    int na = filepath.lastIndexOf("\\");
    String filename = filepath.substring(na + 1);
    // out.println(" Absolute file path: "+filepath+"<br>");
    // out.println(" Filename: "+filename+"<br><br>");
    String path=fpath + filename;
    File fi = new File(path);//  Create Object File 
    if (!fi.exists()&&!fi.createNewFile())
      return -2;
    BufferedOutputStream f = new BufferedOutputStream(new FileOutputStream(
        fi));
    while ((l = in.readLine(b, 0, b.length)) > 0)
    {
      if (l == sign.length())
      {
        String sign1 = new String(b, 0, sign.length());
        // out.println(sign1+"<br>");
        if (sign1.startsWith(sign))//  Compare whether the file has been transferred 
          break;
      }
      f.write(b, 0, l);
      f.flush();
    }
    f.flush();
    f.close();
    long end = System.currentTimeMillis();//  End of transmission time timing 
    // out.println(" Upload time: "+(end-begin)+" Milliseconds <br>");
    return end - begin;
  }
}

2. submitFile. jsp:


<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
  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 'submitFile.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">
    <!--
  <link rel="stylesheet" type="text/css" href="styles.css">
  -->
    <script language="javascript">
      function check()
      {
        if (document.form2.name.value==""){
          alert(" Name cannot be empty! ! ");
          document.form2.name.focus();
          return false;
        }
        if (document.form2.file.value==""){
          alert(" File cannot be empty! ! ");
          return false;
        }
        return true;
      }
    </script>
  </head>
  <body>
    <br>
    <form method="post" name="form2" enctype="MULTIPART/FORM-DATA"
      action="AnswerFile.jsp">
      <br>
      <p align="center">
        &nbsp;
        <br>
      </p>
      <table width="530" border="1" bgcolor="#c0c0c0" align="center"
        height="91">
        <tbody>
          <tr>
            <td valign="top" align="right">
               Name 
              <br>
            </td>
            <td valign="top">
              <input type="text" name="name">
            </td>
          </tr>
          <tr>
            <td align="right">
              &nbsp;  Documents 
            </td>
            <td align="left">
              &nbsp;
              <input type="file" name="file">
            </td>
          </tr>
          <tr>
            <td valign="top" align="right">
               File type 
              <br>
            </td>
            <td valign="top" align="left">
              <select size="1" name="leixing">
                <option selected value=" Homework ">
                   Homework 
                </option>
                <option value=" Curriculum design ">
                   Curriculum design 
                </option>
                <option value=" Thesis ">
                   Thesis 
                </option>
              </select>
            </td>
          </tr>
          <tr>
            <td align="right">
              <input type="Submit" value=" Upload " name="button2" onclick="return(check());">
            </td>
            <td align="left">
              &nbsp;
              <input type="reset" value=" Reset " name="button3">
            </td>
          </tr>
        </tbody>
      </table>
      <p>
        &nbsp;
        <br>
        <br>
        &nbsp;
      </p>
    </form>
  </body>
</html>

3. AnswerFile. jsp:




<%@ page language="java" import="java.util.*,java.io.*"
  pageEncoding="GB18030"%>
<%
  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 'AnswerFile.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">
    <!--
  <link rel="stylesheet" type="text/css" href="styles.css">
  -->
  </head>
  <body>
    <jsp:useBean id="upload" scope="session" class="FileUpload.FileUpload"/>
    <jsp:setProperty name="upload" value="C://" property="fpath"/>
    <%
      ServletInputStream in = request.getInputStream();
      upload.setInputStream(in);
      String nam = upload.getParameter();
      out.println(" Name :" + nam + "<br><br>");
      long time = upload.getFileUpload();
      out.println(" The file upload is completed, and the total time consumption is: " + time + " Milliseconds <br>");
      String leixing = upload.getParameter();
      out.println(" File type: " + leixing + "<br>");
      in.close();
    %>
    <br>
    <div align="right">
      <a href="index.jsp"> Back to the Home Page </a>
    </div>
  </body>
</html>

I hope this article is helpful to everyone's JSP programming.


Related articles: