⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 107.html

📁 关于jsp的一些好文章 主要介绍一些关于JSP的应用技巧方面的东西
💻 HTML
字号:

<STYLE type=text/css>
<!--
body,td { font-size:9pt;}
hr { color: #000000; height: 1px}
-->
</STYLE>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<HTML>
<HEAD><TITLE>精选文章 >> 文件操作 >> 如何在Web页上实现文件上传</title>
</head>
<body >

<p><IMG SRC="../image/jsp001_middle_logo.gif" WIDTH="180" HEIGHT="60" BORDER=0 ALT=""></p>

<table width=100% bgcolor="#cccccc" align=center cellpadding="2" cellspacing="0" border=1 bordercolorlight="#000000" bordercolordark="#FFFFFF">
<tr bgcolor="#EFF8FF"><td>
<a href=http://www.jsp001.com/list_thread.php?int_attribute=2>精选文章</a>
>> <a href=http://www.jsp001.com/list_thread.php?forumid=16&int_attribute=2>文件操作</a>
>> 如何在Web页上实现文件上传 [<a href=http://www.jsp001.com/forum/showthread.php?goto=newpost&threadid=107>查看别人的评论</a>]<br>

<hr><p>由 webmaster 发布于: 2001-01-21 11:08</p><p> </p><p><br>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 &amp;&amp; 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 &lt; formDataLength)<br>    {<br>     //check for maximum file size violation<br>     sizeCheck = totalBytesRead + in.available();<br>     if (sizeCheck &gt; 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\"") &gt; 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("..") &gt; 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\"") &gt; 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\"") &gt; 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\"") &gt; 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></p></td>
  </tr>
</table>

<p>
<CENTER><a href="http://www.jsp001.com/forum/newreply.php?action=newreply&threadid=107">点这里对该文章发表评论</a></CENTER>
<p>该文章总得分是 <font color=red>0</font> 分,你认为它对你有帮助吗?
				[<a href=javascript:void(0) onclick=window.open("http://www.jsp001.com/forum/codeVote.php?threadid=107&intVote=4","","menubar=no,toolbar=no,location=no,directories=no,status=no,resizable=no,scrollbars=no,width=70,height=40,top=0,left=0")>非常多</a>](<font color=red>0</font>) 
				[<a href=javascript:void(0) onclick=window.open("http://www.jsp001.com/forum/codeVote.php?threadid=107&intVote=2","","menubar=no,toolbar=no,location=no,directories=no,status=no,resizable=no,scrollbars=no,width=70,height=40,top=0,left=0")>有一些</a>](<font color=red>0</font>) 
				[<a href=javascript:void(0) onclick=window.open("http://www.jsp001.com/forum/codeVote.php?threadid=107&intVote=1","","menubar=no,toolbar=no,location=no,directories=no,status=no,resizable=no,scrollbars=no,width=70,height=40,top=0,left=0")>无帮助</a>](<font color=red>0</font>) 
				[<a href=javascript:void(0) onclick=window.open("http://www.jsp001.com/forum/codeVote.php?threadid=107&intVote=-1","","menubar=no,toolbar=no,location=no,directories=no,status=no,resizable=no,scrollbars=no,width=70,height=40,top=0,left=0")>是灌水</a>](<font color=red>0</font>) </p>
<script language="javascript" src="http://www.jsp001.com/include/read_thread_script.php?threadid=107"></script>
<p><CENTER>
Copyright &copy; 2001 - 2009 JSP001.com . All Rights Reserved <P>

<IMG SRC="../image/jsp001_small_logo.gif" WIDTH="85" HEIGHT="30" BORDER=0 ALT="">
</CENTER></p>

</body>
</html>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -