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

web|上传

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

时间: 2024-12-07 12:29:19

如何在Web页上实现文件上传的相关文章

如何在Web页面中集成文件上传功能

当前,个人主页制作非常流行.当用户开发好自己的页面时,需要将文件传输到服务器上,解决这个问题的方法之一是运行FTP服务器并将每个用户的FTP默认目录设为用户的Web主目录,这样用户就能运行FTP客户程序并上传文件到指定的 Web目录.由于Windows NT 和 Windows98均不提供直接的基于窗口形式的FTP客户程序,用户必须懂得如何使用基于命令行的FTP客户,或掌握一种新的基于窗口形式的FTP客户程序.因此,这种解决方案仅对熟悉FTP且富有经验的用户来说是可行的. 如果我们能把文件上传功

使用Web Uploader实现多文件上传_javascript技巧

引入资源 使用Web Uploader文件上传需要引入三种资源:JS, CSS, SWF. <!--引入CSS--> <link rel="stylesheet" type="text/css" href="webuploader文件夹/webuploader.css"> <!--引入JS--> <script type="text/javascript" src="webu

Web开发中的文件上传组件uploadify的使用

在Web开发中,有很多可以上传的组件模块,利用HTML的File控件的上传也是一种办法,不过这种方式,需要处理的细节比较多,而且只能支持单文件的操作.在目前Web开发中用的比较多的,可能uploadify(参考http://www.uploadify.com/)也算一个吧,不过这个版本一直在变化,他们的脚本调用也有很大的不同,甚至调用及参数都一直在变化,很早的时候,那个Flash的按钮文字还没法变化,本篇随笔主要根据项目实际,介绍一下3.1版本的uploadify的控件使用,这版本目前还是最新的

如何在web页面实现打开文件对话框功能????

问题描述 求助,如何在web页面实现打开文件对话框功能?请高手帮帮忙! 解决方案 解决方案二:<inputtype=file....

脚本和web页共用同一个文件测试_javascript技巧

脚本和web页共用同一个文件测试

JAVA WEB怎么实现大文件上传(上G的文件)

问题描述 JAVAweb怎么实现上G的文件上传.好像用Struct2对大文件支持有限.比如百度云硬盘,还要邮箱的大附件上传方式.都是用什么技术实现的,activex技术,ftp方式,还是其他什么方式 解决方案 解决方案二:解决这种大文件上传不太可能用web上传的方式,只有自己开发插件或是当门客户端上传,或者用现有的ftp等.1)开发一个web插件.用于上传文件.2)开发一个FTP工具,不用web上传.3)用现有的FTP工具.下面是几款不错的插件,你可以试试:1)Jquery的uploadify插

用Web Services服务实现文件上传

services|web|上传 建立一个Web Services服务,public string UploadFile(byte[] fs,string FileName) { try { ///定义并实例化一个内存流,以存放提交上来的字节数组. MemoryStream m = new MemoryStream(fs); ///定义实际文件对象,保存上载的文件. FileStream f = new FileStream(Server.MapPath("") + "\\&q

如何在web.xml中映射文件夹

问题描述 我的需求是当用户访问/ring/ga03p/地址的时候我想通过web.xml跳到别的地址上去应该如何做比如用户访问http://127.0.0.1/ring/ga03p/?a=1111111但是跳到http://127.0.0.1/c?a=11111十分感谢 解决方案 解决方案二:我没试过,应该不可以,要在服务器内部跳转转一下.解决方案三:配置的时候带上包名.解决方案四:编写一个过滤器就可以了.设置为/ring/ga03p/*只要访问/ring/ga03p/这个目录就可以转到指定的页面

Web应用安全之八种安全的文件上传方式(1)

为了让最终用户将 文件上传到您的网站,就像是给危及您的服务器的恶意用户打开了另一扇门.即便如此,在今天的现代互联网的Web应用程序,它是一种常见的要求,因为它有助于提高您的业务效率.在Facebook和Twitter等社交网络的Web应用程序,允许文件上传.也让他们在博客,论坛,电子银行网站,YouTube和企业支持门户,给机会给最终用户与企业员工有效地共享文件.允许用户上传图片,视频,头像和许多其他类型的文件.498)this.w idth=498;' onmousewheel = 'java