如何在Web页上实现文件上传

原创 2001年05月15日 16:44:00
 
 

public class UploadServlet extends HttpServlet
{
  //default maximum allowable file size is 100k
  static final int MAX_SIZE = 102400;
  //instance variables to store root and success message
  String rootPath, successMessage;
  /**
   * init method is called when servlet is initialized.
   */
  public void init(ServletConfig config) throws ServletException
  {
    super.init(config);
    //get path in which to save file
    rootPath = config.getInitParameter("RootPath");
    if (rootPath == null)
    {
      rootPath = "/";
    }
    /*Get message to show when upload is complete. Used only if
      a success redirect page is not supplied.*/
    successMessage = config.getInitParameter("SuccessMessage");
    if (successMessage == null)
    {
      successMessage = "File upload complete!";
    }
  }
  /**
   * doPost reads the uploaded data from the request and writes
   * it to a file.
   */
  public void doPost(HttpServletRequest request,
    HttpServletResponse response)
  {
    ServletOutputStream out=null;
    DataInputStream in=null;
    FileOutputStream fileOut=null;
    try
    {
      /*set content type of response and get handle to output
        stream in case we are unable to redirect client*/
      response.setContentType("text/plain");
      out = response.getOutputStream();
    }
    catch (IOException e)
    {
      //print error message to standard out
      System.out.println("Error getting output stream.");
      System.out.println("Error description: " + e);
      return;
    }
    try
    {
      //get content type of client request
      String contentType = request.getContentType();
      //make sure content type is multipart/form-data
      if(contentType != null && contentType.indexOf(
        "multipart/form-data") != -1)
      {
        //open input stream from client to capture upload file
        in = new DataInputStream(request.getInputStream());
        //get length of content data
        int formDataLength = request.getContentLength();
        //allocate a byte array to store content data
        byte dataBytes[] = new byte[formDataLength];
        //read file into byte array
        int bytesRead = 0;
        int totalBytesRead = 0;
        int sizeCheck = 0;
        while (totalBytesRead < formDataLength)
        {
          //check for maximum file size violation
          sizeCheck = totalBytesRead + in.available();
          if (sizeCheck > MAX_SIZE)
          {
            out.println("Sorry, file is too large to upload.");
            return;
          }
          bytesRead = in.read(dataBytes, totalBytesRead,
            formDataLength);
          totalBytesRead += bytesRead;
        }
        //create string from byte array for easy manipulation
        String file = new String(dataBytes);
        //since byte array is stored in string, release memory
        dataBytes = null;
        /*get boundary value (boundary is a unique string that
          separates content data)*/
        int lastIndex = contentType.lastIndexOf("=");
        String boundary = contentType.substring(lastIndex+1,
          contentType.length());
        //get Directory web variable from request
        String directory="";
        if (file.indexOf("name=/"Directory/"") > 0)
        {
          directory = file.substring(
            file.indexOf("name=/"Directory/""));
          //remove carriage return
          directory = directory.substring(
            directory.indexOf("/n")+1);
          //remove carriage return
          directory = directory.substring(
            directory.indexOf("/n")+1);
          //get Directory
          directory = directory.substring(0,
            directory.indexOf("/n")-1);
          /*make sure user didn't select a directory higher in
            the directory tree*/
          if (directory.indexOf("..") > 0)
          {
            out.println("Security Error: You can't upload " +
              "to a directory higher in the directory tree.");
            return;
          }
        }
        //get SuccessPage web variable from request
        String successPage="";
        if (file.indexOf("name=/"SuccessPage/"") > 0)
        {
          successPage = file.substring(
            file.indexOf("name=/"SuccessPage/""));
          //remove carriage return
          successPage = successPage.substring(
            successPage.indexOf("/n")+1);
          //remove carriage return
          successPage = successPage.substring(
            successPage.indexOf("/n")+1);
          //get success page
          successPage = successPage.substring(0,
            successPage.indexOf("/n")-1);
        }
        //get OverWrite flag web variable from request
        String overWrite;
        if (file.indexOf("name=/"OverWrite/"") > 0)
        {
          overWrite = file.substring(
            file.indexOf("name=/"OverWrite/""));
          //remove carriage return
          overWrite = overWrite.substring(
            overWrite.indexOf("/n")+1);
          //remove carriage return
          overWrite = overWrite.substring(
            overWrite.indexOf("/n")+1);
          //get overwrite flag
          overWrite = overWrite.substring(0,
            overWrite.indexOf("/n")-1);
        }
        else
        {
          overWrite = "false";
        }
        //get OverWritePage web variable from request
        String overWritePage="";
        if (file.indexOf("name=/"OverWritePage/"") > 0)
        {
          overWritePage = file.substring(
            file.indexOf("name=/"OverWritePage/""));
          //remove carriage return
          overWritePage = overWritePage.substring(
            overWritePage.indexOf("/n")+1);
          //remove carriage return
          overWritePage = overWritePage.substring(
            overWritePage.indexOf("/n")+1);
          //get overwrite page
          overWritePage = overWritePage.substring(0,
            overWritePage.indexOf("/n")-1);
        }
        //get filename of upload file
        String saveFile = file.substring(
          file.indexOf("filename=/"")+10);
        saveFile = saveFile.substring(0,
          saveFile.indexOf("/n"));
        saveFile = saveFile.substring(
          saveFile.lastIndexOf("//")+1,
          saveFile.indexOf("/""));
        /*remove boundary markers and other multipart/form-data
          tags from beginning of upload file section*/
        int pos; //position in upload file
        //find position of upload file section of request
        pos = file.indexOf("filename=/"");
        //find position of content-disposition line
        pos = file.indexOf("/n",pos)+1;
        //find position of content-type line
        pos = file.indexOf("/n",pos)+1;
        //find position of blank line
        pos = file.indexOf("/n",pos)+1;
        /*find the location of the next boundary marker
          (marking the end of the upload file data)*/
        int boundaryLocation = file.indexOf(boundary,pos)-4;
        //upload file lies between pos and boundaryLocation
        file = file.substring(pos,boundaryLocation);
        //build the full path of the upload file
        String fileName = new String(rootPath + directory +
          saveFile);
        //create File object to check for existence of file
        File checkFile = new File(fileName);
        if (checkFile.exists())
        {
          /*file exists, if OverWrite flag is off, give
            message and abort*/
          if (!overWrite.toLowerCase().equals("true"))
          {
            if (overWritePage.equals(""))
            {
              /*OverWrite HTML page URL not received, respond
                with generic message*/
              out.println("Sorry, file already exists.");
            }
            else
            {
              //redirect client to OverWrite HTML page
              response.sendRedirect(overWritePage);
            }
            return;
          }
        }
        /*create File object to check for existence of
          Directory*/
        File fileDir = new File(rootPath + directory);
        if (!fileDir.exists())
        {
          //Directory doesn't exist, create it
          fileDir.mkdirs();
        }
        //instantiate file output stream
        fileOut = new FileOutputStream(fileName);
        //write the string to the file as a byte array
        fileOut.write(file.getBytes(),0,file.length());
        if (successPage.equals(""))
        {
          /*success HTML page URL not received, respond with
            generic success message*/
          out.println(successMessage);
          out.println("File written to: " + fileName);
        }
        else
        {
          //redirect client to success HTML page
          response.sendRedirect(successPage);
        }
      }
      else //request is not multipart/form-data
      {
        //send error message to client
        out.println("Request not multipart/form-data.");
      }
    }
    catch(Exception e)
    {
      try
      {
        //print error message to standard out
        System.out.println("Error in doPost: " + e);
        //send error message to client
        out.println("An unexpected error has occurred.");
        out.println("Error description: " + e);
      }
      catch (Exception f) {}
    }
    finally
    {
      try
      {
        fileOut.close(); //close file output stream
      }
      catch (Exception f) {}
      try
      {
        in.close(); //close input stream from client
      }
      catch (Exception f) {}
      try
      {
        out.close(); //close output stream to client
      }
      catch (Exception f) {}
    }
  }
}


 

单页WEB应用(三),Chat聊天模块

Chat 聊天模块这个模块应该就是该书全篇的唯一一个模块吧,后面几乎所有的篇章都围绕这个模块去实现的,不过就通过这一个模块的实现和上线,也能体现单页应用开发到发布上线的整个过程,毕竟后面的数据,通信,...
  • gccll
  • gccll
  • 2017年02月15日 17:30
  • 1145

一个简单的Web标签页

基于jQuery的tag标签设计
  • Yu_Web
  • Yu_Web
  • 2016年11月07日 21:01
  • 610

web广告推送功能开发总结

公司业务需要支持web
  • h721510279812
  • h721510279812
  • 2014年09月05日 19:08
  • 1160

SPA单页WEB应用博客开始第一篇--2015-03-28

入职新公司后,工作从后端转到前端,以后的工作也围绕前端,因此开了一个新的栏目记录下学习前端的一些知识点和总结。同事也是对刚买的新书【单页WEB应用JavaScript从前端到后端】的读书笔记。从后端到...
  • ivan0609
  • ivan0609
  • 2015年03月28日 16:00
  • 1783

单页WEB应用(一),结构和布局

单页WEB应用(一),结构和布局前两天买了两本书,一本《基于MVC的Javascript Web富应用开发》这本拿到手第二天大概的翻了一遍,没怎么深入去看,主要前面讲的基本的一些东西,后面的有些还没太...
  • gccll
  • gccll
  • 2017年02月10日 18:10
  • 1732

基于Selenium的web自动化框架(python)

1 什么是selenium Selenium 是一个基于浏览器的自动化工具,它提供了一种跨平台、跨浏览器的端到端的web自动化解决方案。Selenium主要包括三部分:Selenium IDE、Sel...
  • xinke453
  • xinke453
  • 2017年06月11日 15:39
  • 516

单页Web应用程序

单页Web应用程序的优点: 首先,最大的好处是用户体验,对于内容的改动不需要加载整个页面。这样做好处颇多,因为数据层和UI的分离,可以重新编写一个原生的移动设备应用程序而不用(对原有数据服务部分...
  • u010080803
  • u010080803
  • 2016年04月22日 00:14
  • 488

主题和母版页 如何在web窗体调用操作母版页内容元素

标准化网站布局        标准化网站布局的格式只是整个过程的一部分,你还需要保证通用的元素,如网站的标题、网站的导航控件等在每个页面里都出现在相同的位置。解决这一问题的关键在于创建一个可以重...
  • bensidiyu
  • bensidiyu
  • 2015年07月14日 15:30
  • 3915

Web母版制作和母版嵌套

母版是网页制作中很重要的一部分,它可以大大节省web开发的过程,避免过多重复性的制作过程;而母版嵌套是在沿用母版的基础上进一步进行格式化的方法。...
  • mengdonghui123456
  • mengdonghui123456
  • 2015年09月04日 16:29
  • 2131

如何在网站中添加音乐

来源:http://www.ido321.com/1042.html 发现有很多的个人博客中添加了背景音乐,以增强用户体验。LZ搜集到了两种在网站中添加音乐的方式。 一、豆瓣的FM ...
  • u011043843
  • u011043843
  • 2014年10月19日 12:26
  • 1765
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:如何在Web页上实现文件上传
举报原因:
原因补充:

(最多只允许输入30个字)