Topic: 一个上传文件的程序!请教!

  Print this page

1.一个上传文件的程序!请教! Copy to clipboard
Posted by: asdlcj
Posted on: 2003-06-24 16:33

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class UploadServlet extends HttpServlet
{
//default maximum allowable file size is 1000k
static final int MAX_SIZE = 1024000;
//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();
  
    //get content type of client request
    String contentType = request.getContentType();
    out.println("\ncontentType= " + contentType);
    
    //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();
      out.println("\nContentLength= " + formDataLength);
      
      //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 fileStr = new String(dataBytes,"ISO8859_1");
      
      //Debuge
      out.println("*** The content of entity Body is:\n");
      out.println(fileStr);
      out.println("*** End of entity body!\n");
      
      //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 the filename of upload file
      String tempStr = fileStr.substring(fileStr.indexOf("filename=\"")+10);
      tempStr = tempStr.substring(0,tempStr.indexOf("\n"));
      tempStr = tempStr.substring(tempStr.lastIndexOf("\\")+1,tempStr.indexOf("\""));
      String fileName = new String(tempStr);
            
      /*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 = fileStr.indexOf("filename=\"");
      //find position of content-disposition line
      pos = fileStr.indexOf("\n",pos)+1;
      //find position of content-type line
      pos = fileStr.indexOf("\n",pos)+1;
      //find position of blank line
      pos = fileStr.indexOf("\n",pos)+1;
      /*find the location of the next boundary marker
      (marking the end of the upload file data)*/
      int boundaryLocation = fileStr.indexOf(boundary,pos)-4;
      //upload file lies between pos and boundaryLocation
      fileStr = fileStr.substring(pos,boundaryLocation);
      //build the full path of the upload file
      
      //instantiate file output stream
      fileOut = new FileOutputStream(rootPath+fileName);
      //write the string to the file as a byte array
      fileOut.write(fileStr.getBytes("ISO8859_1"),0,fileStr.length());
      out.println(successMessage);
      out.println("File written to: " + fileName);
    }
    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) {}
  }
}
}
我写一个jsp!
能成功上传!
但不知道传到哪了?
书上说!到tomcat根目录!
我找不到啊!

2.Re:一个上传文件的程序!请教! [Re: asdlcj] Copy to clipboard
Posted by: 1255
Posted on: 2003-06-24 17:20

用搜索的
就可以找到了

3.Re:一个上传文件的程序!请教! [Re: asdlcj] Copy to clipboard
Posted by: asdlcj
Posted on: 2003-06-24 22:28

大哥!我试了!就找不 到啊!
怎么回事啊?
要不自己设置一下上传路径!
怎么搞啊?

4.Re:一个上传文件的程序!请教! [Re: asdlcj] Copy to clipboard
Posted by: 牛老板
Posted on: 2003-06-24 22:54

win:

dir/a/s filename

unix/linux:

find / -name filename

先找到上传的文件在哪里的说.....................

5.Re:一个上传文件的程序!请教! [Re: asdlcj] Copy to clipboard
Posted by: asdlcj
Posted on: 2003-06-24 23:20

好的!我试试!谢谢拉

是不是这样
E:\dir\a\s webwhere
?

[this isn't a chat board, you may try the edit function in the future.
Don't you know anything of DOS command?
please check Windows Help for the dir command.
actually /a isn't useful in this case
dir /s yourfilename
/s Lists every occurrence, in the specified directory and all subdirectories, of the specified file name.]

6.Re:一个上传文件的程序!请教! [Re: asdlcj] Copy to clipboard
Posted by: asdlcj
Posted on: 2003-06-25 10:28

我只知道dir是显示的功能啊!谢了
我用了!竟然找不到啊 !
我贴出<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb_2312-80">
<title>Upload a File</title>
</head>
<body>
<h1>文件上传 </h1>
<h2>提示:您的浏览器必须能支持文件上传!</h2>
<form action="http://localhost:8080/examples/servlet/UploadServlet" method="POST" enctype="multipart/form-data">
<div align="left">
  <pre>发送文件:<input type="file" size="40" name="upl-file"> </BR>
  <input type="submit" value="开始发送" now> <input type="reset" value="重 设"></pre>
</div>
</form>

</body>
</html>

7.Re:一个上传文件的程序!请教! [Re: asdlcj] Copy to clipboard
Posted by: leowu2000
Posted on: 2003-06-25 18:16

很可能是在Tomcat启动菜单快捷方式所在的目录里边。

8.Re:一个上传文件的程序!请教! [Re: asdlcj] Copy to clipboard
Posted by: asdlcj
Posted on: 2003-06-25 23:39

真奇怪啊!
找不到!
飞到哪?
还是smartload好


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923